我想发布到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而不是内置的格式化程序.
解决方法
你试过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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。