Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net WebApi HttpClient Strongly Typed PostAync

I am trying to post to a Asp.Net WebApi Post Method:

 // POST /api/citycode
public HttpResponseMessage<CityCode> Post(CityCode citycode)
{
    try
    {
        Test.SelfTrackingEntities.BusinessLayer.BusinessManagers.CityCodeManager myCityCodeManager = new CityCodeManager(Utility.GetConnectionString());
        var id = myCityCodeManager.Create(citycode);

        var response = new HttpResponseMessage<Test.SelfTrackingEntities.BusinessLayer.BusinessEntities.CityCode>(citycode) { StatusCode = HttpStatusCode.Created };
        response.Headers.Location = new Uri(VirtualPathUtility.AppendTrailingSlash(Request.RequestUri.ToString()) + citycode.Name);
        return response;
    }
    catch (Exception e)
    {
        var response = new HttpResponseMessage(HttpStatusCode.Conflict);
        response.Content = new StringContent(e.Message);
        throw new HttpResponseException(response);
    }
}

The Client Call is:

var objectContent = CreateJsonObjectContent(citycode);
objectContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var requestMessage = new HttpRequestMessage<CityCode>(citycode, jsonMediaType);
return httpClient.PostAsync(addressSuffix, objectContent).ContinueWith(task =>
{
    var responseMessage = task.Result;
    return responseMessage.Content.ReadAsAsync<CityCode>().ContinueWith(readTask =>
    {
        return readTask.Result;
    });
}).Unwrap();

But the server never Receives the call, I am using the JsonNetFormatter not the built in formatter.

like image 689
Tom B Avatar asked May 29 '12 14:05

Tom B


1 Answers

Have you tried the HttpClient (http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx)?

This is an excellent HTTP client for consuming MVC 4 Web Api. Take a look at this:

        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

        var server = new HttpServer(config);
        var client = new HttpClient(server);

        dynamic s = new ExpandoObject();
        s.comeValue = 1;

        var d = JsonConvert.SerializeObject(s);
        var content = new StringContent(d, Encoding.UTF8, "application/json");

        var postResult = client.PostAsync("http://localhost:29722/api/whatevercontroller", content).Result;
like image 185
Mads Tjørnelund Toustrup Avatar answered Sep 28 '22 08:09

Mads Tjørnelund Toustrup