使用 PostAsync、HttpClient 和 Json 从 C# Metro UI 客户端调用 MVC4 WebAPI 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9863138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling MVC4 WebAPI methods from C# Metro UI Client using PostAsync, HttpClient & Json
提问by INNVTV
I've created a method using the new WebAPI features in MVC4 and have it running on Azure. The method requires that you post a simple LoginModel object that consists of a Username and Password property. Yes, I plan on securing this further once I get past this speed bump :-) The method then responds with an object in Json format:
我已经使用 MVC4 中的新 WebAPI 功能创建了一个方法,并让它在 Azure 上运行。该方法要求您发布一个由用户名和密码属性组成的简单 LoginModel 对象。是的,我计划在我通过这个减速带后进一步确保这一点:-) 然后该方法以 Json 格式的对象进行响应:


I can successfully call this method using Fiddler, provided that I include "Content-Type: application/json" in the Request Headers. It returns with 200 and I can go into the Fiddler Inspector and view the Json response object just fine:
我可以使用 Fiddler 成功调用此方法,前提是我在请求标头中包含“Content-Type: application/json”。它返回 200,我可以进入 Fiddler Inspector 并查看 Json 响应对象就好了:


I am however having problems calling this same method from a MetroUI app in Windows8 using C#/XAML. I began playing around with the HttpClient and the new Async concepts in C# and no matter how I formatted my Post calls (even when explicitly calling out that I want the Content-Type to be "application/json") Fiddler returns with a 500 error and states that the attempt was using Content-Type:"text/html". I beleive this to be the root of the problem:
但是,我在使用 C#/XAML 从 Windows8 中的 MetroUI 应用程序调用相同的方法时遇到问题。我开始在 C# 中使用 HttpClient 和新的 Async 概念,无论我如何格式化我的 Post 调用(即使明确指出我希望 Content-Type 为“application/json”)Fiddler 返回 500 错误并声明该尝试使用的是 Content-Type:"text/html"。我相信这是问题的根源:


I have tried everything conceivable in order to post to this method and get back the Json object, here is my most recent attempt:
我已经尝试了所有可以想到的方法来发布到这个方法并取回 Json 对象,这是我最近的尝试:
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(@"{ ""Username"": """ + Username.Text + @", ""Password"": """ + Password.Text + @"""}");
client.PostAsync("http://myapi.com/authentication", content).ContinueWith(result =>
{
var response = result.Result;
response.EnsureSuccessStatusCode();
});
This results in a 500 error with Content-Type set to "text/html"
这会导致 500 错误,内容类型设置为“text/html”
Here was another attempt which also failed:
这是另一个失败的尝试:
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync("http://myapi.com/authentication", new StringContent(@"{ ""Username"": """ + Username.Text + @", ""Password"": """ + Password.Text + @"""}", Encoding.UTF8, "application/json"));
string statusCode = response.StatusCode.ToString();
Can anyone point me in the right direction?
任何人都可以指出我正确的方向吗?
Just tried the following code thanks to the advice of Nemesv:
由于 Nemesv 的建议,刚刚尝试了以下代码:
HttpClient httpClient = new HttpClient();
HttpContent content = new StringContent(@"{ ""Username"": """ + Username.Text + @", ""Password"": """ + Password.Text + @"""}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await httpClient.PostAsync("http://webapi.com/authentication", content);
string statusCode = response.StatusCode.ToString();
response.EnsureSuccessStatusCode();
It now shows "application/json" in my request header, but still shows "text/html" in the Web Session:
它现在在我的请求标头中显示“application/json”,但在 Web Session 中仍然显示“text/html”:


采纳答案by nemesv
Try this to set the Headers.ContentType:
试试这个来设置Headers.ContentType:
HttpClient httpClient = new HttpClient();
HttpContent content = new StringContent(@"{ ""Username"": """ + "etc." + @"""}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response =
await httpClient.PostAsync("http://myapi.com/authentication", content);
string statusCode = response.StatusCode.ToString();
回答by vast
There is some missing try this is working.
有一些缺失的尝试这是有效的。
UserLoginModel user = new UserLoginModel { Login = "username", Password = "password" };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(user);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:1066/api/");
HttpResponseMessage response = client.PostAsync("Authenticate", content).Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsAsync<ResultModel>().Result;
}
else
{
return string.Empty;
}

