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; } 
2
  • @Stephen I want this post to be done in a client-side program written in C#, without a browser. is it possible? Commented Nov 18, 2014 at 9:33
  • Related post - How to make an HTTP POST web request Commented Sep 6, 2021 at 15:16

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

5 Comments

@Ludovic-From browser? Really??
@RahulSingh Quoting the question: "from a client-side program written in C#, without a browser"
@RahulSingh The OP asked for a client side program
@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!
@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 :)
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; } 

1 Comment

+1 for showing parameter names such as "n", "s" should match in client and server.
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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.