【发布时间】:2012-03-25 19:10:26
【问题描述】:
我使用 MVC4 中的新 WebAPI 功能创建了一个方法,并让它在 Azure 上运行。该方法要求您发布一个简单的 LoginModel 对象,该对象由 Username 和 Password 属性组成。是的,一旦我克服了这个减速带,我计划进一步保护它:-) 然后该方法以 Json 格式的对象响应:
我可以使用 Fiddler 成功调用此方法,前提是我在请求标头中包含“Content-Type: application/json”。它返回 200,我可以进入 Fiddler Inspector 并查看 Json 响应对象就好了:
但是,我在使用 C#/XAML 从 Windows8 中的 MetroUI 应用程序调用相同方法时遇到问题。我开始在 C# 中使用 HttpClient 和新的 Async 概念,无论我如何格式化我的 Post 调用(即使明确指出我希望 Content-Type 为“application/json”)Fiddler 返回一个 500 错误并声明尝试使用 Content-Type:"text/html"。我相信这是问题的根源:
为了发布到这个方法并取回 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();
});
这会导致 Content-Type 设置为“text/html”时出现 500 错误
这是另一个失败的尝试:
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();
谁能指出我正确的方向?
感谢 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();
它现在在我的请求标头中显示“application/json”,但在 Web 会话中仍然显示“text/html”:
【问题讨论】:
标签: c# httpclient windows-8 microsoft-metro asp.net-mvc-4