Wednesday, April 1, 2015

Post to a WebAPI controller from C# with a WebRequest instead of using an HttpClient.

Instead of this you may do this...

string message;
var request = WebRequest.Create("http://www.example.com/api/whatever");
var data = Encoding.ASCII.GetBytes(string.Format("Foo={0}&Bar={1}", "baz", "qux"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var requestStream = request.GetRequestStream())
{
   requestStream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
   using (var reader = new StreamReader(responseStream))
   {
      message = reader.ReadToEnd();
   }
}

 
 

This assumes the Post method returns a HttpResponseMessage wrapping, in this case, a string like so:

return Request.CreateResponse(HttpStatusCode.OK, "hi there");

No comments:

Post a Comment