使用PostAsync,HttpClient和Json从C#Metro UI客户端调用MVC4 WebAPI方法

我已经使用MVC4中的新WebAPIfunction创建了一个方法,并让它在Azure上运行。 该方法要求您发布一个包含Username和Password属性的简单LoginModel对象。 是的,我计划在经过这个减速带后再进一步确保这个:-)然后该方法以Json格式响应一个对象:

在此处输入图像描述

我可以使用Fiddler成功调用此方法,前提是我在请求标头中包含“Content-Type:application / json”。 它返回200,我可以进入Fiddler检查器并查看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”:

在此处输入图像描述

试试这个来设置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(); 

有一些缺失尝试这是有效的。

 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().Result; } else { return string.Empty; }