Asp.net Web Api HttpClient 强类型 PostAsync

Posted

技术标签:

【中文标题】Asp.net Web Api HttpClient 强类型 PostAsync【英文标题】:Asp.net WebApi HttpClient Strongly Typed PostAync 【发布时间】:2012-05-29 14:55:25 【问题描述】:

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

 // 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】:

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

这是一个使用 MVC 4 Web Api 的优秀 HTTP 客户端。看看这个:

        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;

【讨论】:

以上是关于Asp.net Web Api HttpClient 强类型 PostAsync的主要内容,如果未能解决你的问题,请参考以下文章

Asp.Net Web API 2第三课——.NET客户端调用Web API

Web API1.1 ASP.NET Web API入门

Asp.Net Web API 2第六课——Web API路由和动作选择

Asp.Net Web API 2第十三课——ASP.NET Web API中的JSON和XML序列化

Asp.Net Web API 2第七课——Web API异常处理

将文件从 ASP.NET Core Web api 发布到另一个 ASP.NET Core Web api