我使用MVC4中的新WebAPI功能创建了一个方法,并让它在Azure上运行。该方法要求您发布一个包含Username和Password属性的简单LoginModel对象。是的,我计划在经过这个减速带后再进一步确保这个:-)然后该方法以Json格式响应一个对象:
如果我在请求标头中包含“Content-Type:application / json”,我可以使用Fiddler成功调用此方法。它返回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();
});
这导致500错误,Content-Type设置为“text / html”
这是另一次失败的尝试:
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 Session中显示“text / html”:
答案 0 :(得分:22)
尝试此操作以设置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();
答案 1 :(得分:6)
有一些遗漏尝试这是有效的。
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;
}