asp.net-mvc – 控制台应用程序HttpClient发布到mvc web api
发布时间:2020-12-15 20:52:07 所属栏目:asp.Net 来源:网络整理
导读:我有一个从Visual Studio 2012模板构建的默认mvc web api实例.它在默认的ValuesController中有以下路由和post方法 – MVC站点在初始创建时不会修改,而不是Post方法的内容.此外,我正在使用.NET framework 4.0,因为我计划将Azure作为目标. 注册方法 public sta
我有一个从Visual Studio 2012模板构建的默认mvc web api实例.它在默认的ValuesController中有以下路由和post方法 – MVC站点在初始创建时不会修改,而不是Post方法的内容.此外,我正在使用.NET framework 4.0,因为我计划将Azure作为目标.
注册方法 public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional } ); } 和Post方法 // POST api/values public string Post([FromBody]string value) { if (value != null) { return "Post was successful"; } else return "invalid post,value was null"; } 我创建了一个控制台应用程序,它使用HttpClient来模拟发布到服务,但不幸的是,进入Post的“值”始终为null.在HttpClient上的PostAsync调用之后成功命中了Post方法. 我不清楚如何映射我的请求,以便值包含我传入的StringContent … static void Main(string[] args) { string appendUrl = string.Format("api/values"); string totalUrl = "http://localhost:51744/api/values"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Accept","application/xml"); string content = "Here is my input string"; StringContent sContent = new StringContent(content,Encoding.UTF8,"application/xml"); HttpResponseMessage response = null; string resultString = null; client.PostAsync(new Uri(totalUrl),sContent).ContinueWith(responseMessage => { response = responseMessage.Result; }).Wait(); response.Content.ReadAsStringAsync().ContinueWith(stream => { resultString = stream.Result; }).Wait(); } 我是MVC web api的新手,并且使用了HttpClient – 任何帮助我指向正确方向的人都会非常感激. 解决方法
请尝试以下代码:
class Program { static void Main(string[] args) { HttpClient client = new HttpClient(); var content = new StringContent("=Here is my input string"); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); client.PostAsync("http://localhost:2451/api/values",content) .ContinueWith(task => { var response = task.Result; Console.WriteLine(response.Content.ReadAsStringAsync().Result); }); Console.ReadLine(); } } 请查看此博客文章的“发送简单类型”部分:http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 在ASP.NET MVC 3应用程序中引用类库中的Nin
- 如何在回发后重置asp.net表单?
- asp-classic – 如何在经典ASP中使用VBScript生成MD5?
- asp.net-mvc – MVC4单页应用程序 – 多个屏幕
- ASP.NET MVC:访问日志
- asp.net-mvc – MVC发布复杂对象的列表
- asp.net – Paypal Express Checkout集成问题(WEBREQUEST)
- asp.net – AttachDbFilename的问题是什么
- asp.net-mvc – 任何支持ASP.NET MVC的图表控件,支持具有不
- asp.net-mvc – 用于对Office 365 AD进行身份验证的MVC