Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call HttpPost method from Client in C# code

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

For a HttpPost Controller like below, how do to call this method directly from a client-side 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 am sure the answer is somehwere on the web, but haven't found one so far. Any help is appreciated!

[HttpPost]
public Boolean PostDataToDB(int n, string s)
{
    //validate and write to database
    return false;
}
like image 631
totoro Avatar asked Nov 18 '14 09:11

totoro


People also ask

How do I use HttpPost?

To send data using the HTTP POST method, you must include the data in the body of the HTTP POST message and specify the MIME type of the data with a Content-Type header. Below is an example of an HTTP POST request to send JSON data to the server. The size and data type for HTTP POST requests is not limited.

How do you call a post method in C#?

Serialize(user); var data = new StringContent(json, Encoding. UTF8, "application/json"); var url = "https://httpbin.org/post"; using var client = new HttpClient(); var response = await client. PostAsync(url, data); string result = response.

What is HttpPost C#?

HttpGet and HttpPost are both the methods of posting client data or form data to the server. HTTP is a HyperText Transfer Protocol that is designed to send and receive the data between client and server using web pages.

Can we do POST using GET method?

Never use GET and use POST. Never use POST and use GET. It doesn't matter which one you use.


1 Answers

For example with this code in the server side:

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

You can use different approches:

With WebClient:

using (var wb = new WebClient())
{
    var data = new NameValueCollection();
    data["n"] = "42";
    data["s"] = "string value";
    
    var response = wb.UploadValues("http://www.example.org/receiver.aspx", "POST", data);
}

With HttpRequest:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.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();

With HttpClient:

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

    var content = new FormUrlEncodedContent(values);

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

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

With WebRequest

WebRequest request = WebRequest.Create ("http://www.example.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

like image 131
Ludovic Feltz Avatar answered Oct 17 '22 05:10

Ludovic Feltz