简体   繁体   English

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

[英]Calling MVC4 WebAPI methods from C# Metro UI Client using PostAsync, HttpClient & Json

I've created a method using the new WebAPI features in MVC4 and have it running on Azure. 我已经使用MVC4中的新WebAPI功能创建了一个方法,并让它在Azure上运行。 The method requires that you post a simple LoginModel object that consists of a Username and Password property. 该方法要求您发布一个包含Username和Password属性的简单LoginModel对象。 Yes, I plan on securing this further once I get past this speed bump :-) The method then responds with an object in Json format: 是的,一旦我超过这个减速带,我计划进一步确保这个:-)然后该方法以Json格式响应一个对象:

在此输入图像描述

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

在此输入图像描述

I am however having problems calling this same method from a MetroUI app in Windows8 using C#/XAML. 然而,我在使用C#/ XAML从Windows8中的MetroUI应用程序调用此相同方法时遇到问题。 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". 我开始在C#中使用HttpClient和新的Async概念,无论我如何格式化我的Post调用(即使明确地调用我希望Content-Type为“application / json”)Fiddler返回500错误并声明该尝试使用的是Content-Type:“text / html”。 I beleive this to be the root of the problem: 我相信这是问题的根源:

在此输入图像描述

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错误,Content-Type设置为“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”:

在此输入图像描述

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();

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#Metro HttpClient未在PostAsync上接收cookie - C# Metro HttpClient not receiving cookie on PostAsync 使用PostAsync,HttpClient和Json从Windows Phone 8.1调用REST - Calling REST from Windows Phone 8.1 using PostAsync, HttpClient & Json httpClient.PostAsync(URL,content)在C#Metro应用中不起作用 - httpClient.PostAsync(url, content) not working in C# Metro apps 在 C# 中使用带有 API 密钥的 HttpClient 类中的 PostAsync 方法 - Using PostAsync method from HttpClient Class with an API key in C# C#HttpClient PostAsync与VSO git API的JSON参数 - C# HttpClient PostAsync with JSON parameter for VSO git API 具有自定义标头和主体C#的application / json的HttpClient postasync - HttpClient postasync with custom header and application/json for body C# 从统一C#将json字符串发布到webAPI; HttpClient还是UnityWebRequest? - POST json string to webAPI from unity C#; HttpClient or UnityWebRequest? 如何使用 C# HttpClient PostAsync 显示上传进度 - How to display upload progress using C# HttpClient PostAsync 无法将JSON对象从Rest Client传递到MVC4控制器C# - Not able to pass JSON object from Rest Client to MVC4 controller C# 从MVC4中的JavaScript调用C#方法 - Calling C# method from javascript in MVC4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM