6

我正在尝试发布到 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 而不是内置的格式化程序。

4

1 回答 1

4

您是否尝试过 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;
于 2012-07-06T14:15:25.683 回答