Call HttpPost method from client in C # code

I am new to MVC and C #, so sorry if this question seems too simple.

For HttpPost Controller as below, how to call this method directly from a client program written in C #, without a browser (NOT from a UI form in a browser with a submit button)? I am using .NET 4 and MVC 4.

I'm sure there is an answer on the internet, but I haven't found one yet. Any help is appreciated!

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
    //validate and write to database
    return false;
}

      

+4


source to share


4 answers


For example with this server side code:

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
    //validate and write to database
    return false;
}

      

You can use different settings:

From WebClient

:

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["n"] = "42";
    data["s"] = "string value";

    var response = wb.UploadValues("http://www.domain.org/receiver.aspx", "POST", data);
}

      

From HttpRequest

:



var request = (HttpWebRequest)WebRequest.Create("http://www.domain.org/receiver.aspx");

var postData = "n=42&s=string value";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

      

From HttpClient

:

using (var client = new HttpClient())
{
    var values = new List<KeyValuePair<string, string>>();
    values.Add(new KeyValuePair<string, int>("n", "42"));
    values.Add(new KeyValuePair<string, string>("s", "string value"));

    var content = new FormUrlEncodedContent(values);

    var response = await client.PostAsync("http://www.domain.org/receiver.aspx", content);

    var responseString = await response.Content.ReadAsStringAsync();
}

      

FROM WebRequest

WebRequest request = WebRequest.Create ("http://www.domain.org/receiver.aspx");
request.Method = "POST";
string postData = "n=42&s=string value";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();

//Response
WebResponse response = request.GetResponse ();
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();

      

see msdn

+15


source


You can use First of all, you must return a valid result:

[HttpPost]
public ActionResult PostDataToDB(int n, string s)
{
    //validate and write to database
    return Json(false);
}

      

After that, you can use the HttpClient class from the Web Api NuGet Client Libraries:



public async bool CallMethod()
{
    var rootUrl = "http:...";
    bool result;
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(_rootUrl);
        var response= await client.PostAsJsonAsync(methodUrl, new {n = 10, s = "some string"}); 
        result = await response.Content.ReadAsAsync<bool>();
    }

    return result;
}

      

You can also use the WebClient class:

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
    //validate and write to database
    return false;
}

public async bool CallMethod()
    {
        var rootUrl = "http:...";
        bool result;
        using (var client = new WebClient())
        {
            var col = new NameValueCollection();
            col.Add("n", "1");
            col.Add("s", "2");
            var res = await client.UploadValuesAsync(address, col);
            string res = Encoding.UTF8.GetString(res);

            result = bool.Parse(res);
        }

    return result;
}

      

+1


source


If you choose to use the HttpClient. Do not create or delete HttpClient for every API call. Instead, reuse a single HttpClient instance. You can achieve this by declaring the instance static or by implementing the singleton pattern.

Link: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

How to implement a singleton (good starting point, read the comments on this post): https://codereview.stackexchange.com/questions/149805/implementation-of-a-singleton-httpclient-with-generic-methods

0


source


Hope the below code will help you

[ActionName("Check")]
public async System.Threading.Tasks.Task<bool> CheckPost(HttpRequestMessage request)
{
    string body = await request.Content.ReadAsStringAsync();
    return true;
}

      

0


source







All Articles