call HttpPost method from Client in C# code

33,220

Solution 1

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

Solution 2

You can use First of all you should return valid resutl:

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

After it you can use HttpClient class from Web Api client libraries NuGet package:

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 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;
}
Share:
33,220
totoro
Author by

totoro

Updated on July 21, 2022

Comments

  • totoro
    totoro almost 2 years

    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;
    }
    
  • Rahul Singh
    Rahul Singh over 9 years
    @Ludovic-From browser? Really??
  • J. Steen
    J. Steen over 9 years
    @RahulSingh Quoting the question: "from a client-side program written in C#, without a browser"
  • Ludovic Feltz
    Ludovic Feltz over 9 years
    @RahulSingh The OP asked for a client side program
  • totoro
    totoro over 9 years
    @Ludovic thanks for all the approaches! took me a while to realize the argument parameters on the server side should match that with the client. thanks again!
  • totoro
    totoro over 9 years
    +1 for showing parameter names such as "n", "s" should match in client and server.
  • Ludovic Feltz
    Ludovic Feltz over 9 years
    @dragon_cat Sorry i didn't used your parameter ! i will edit my post to show that it has to match with server side parameters :)