6

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;
}
totoro
  • 3,257
  • 5
  • 39
  • 61
  • @Stephen I want this post to be done in a client-side program written in C#, without a browser. is it possible? – totoro Nov 18 '14 at 09:33
  • Related post - [How to make an HTTP POST web request](https://stackoverflow.com/q/4015324/465053) – RBT Sep 06 '21 at 15:16

4 Answers4

22

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

Amicable
  • 3,115
  • 3
  • 49
  • 77
Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
1

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;
}
0

If you decide to use HttpClient implementation. Do not create and dispose of HttpClient for each call to the API. Instead, re-use a single instance of HttpClient. You can achieve that declaring the instance static or implementing a singleton pattern.

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

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

Miguel
  • 1,575
  • 1
  • 27
  • 31
-1

Hopefully 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;
}
SimonC
  • 1,547
  • 1
  • 19
  • 43
Tahir Rehman
  • 332
  • 2
  • 9