Asp.net WebApi HttpClient强类型PostAync

时间:2012-05-29 14:55:25

标签: asp.net asp.net-web-api dotnet-httpclient

我正在尝试发布到Asp.Net WebApi Post方法:

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

客户来电是:

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();

但是服务器从不接收呼叫,我使用的是JsonNetFormatter而不是内置的格式化程序。

1 个答案:

答案 0 :(得分:4)

您是否尝试过HttpClient(http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx)?

这是一个出色的HTTP客户端,用于使用MVC 4 Web Api。看看这个:

        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;