如何在Web Api中使用带有响应的Httpclient获取对象

Aqd*_*das 15 c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api2

我的网络api喜欢

    public async Task<IHttpActionResult> RegisterUser(User user)
    {
        //User Implementation here

        return Ok(user);
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用HTTPClient来请求web api,如下所述.

var client = new HttpClient();
string json = JsonConvert.SerializeObject(model);
var result = await client.PostAsync( "api/users", new StringContent(json, Encoding.UTF8, "application/json"));
Run Code Online (Sandbox Code Playgroud)

在我的结果请求中可以找到在客户端应用程序上实现的用户对象?

Rob*_*ert 31

您可以使用(对所需内容进行depand),并将其反序列化回用户对象.

await result.Content.ReadAsByteArrayAsync();
//or
await result.Content.ReadAsStreamAsync();
//or
await result.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

Fe,如果你的web api正在返回JSON,你可以使用

var user = JsonConvert.DeserializeObject<User>( await result.Content.ReadAsStringAsync());
Run Code Online (Sandbox Code Playgroud)

编辑:正如cordan所指出的,您还可以添加参考System.Net.Http.Formatting和使用:

await result.Content.ReadAsAsync<User>()
Run Code Online (Sandbox Code Playgroud)

  • 为什么不直接使用`await result.Content.ReadAsAsync <User>()`? (5认同)
  • 如果您使用的是dotnet内核,请安装[Microsoft.AspNet.WebApi.Client /](https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/),然后就可以使用ReadAsAsync &lt;T&gt;() (2认同)
  • 这真的应该被接受的答案......你不觉得吗? (2认同)

See*_* As 5

string Baseurl = GetBaseUrl(microService);
string url = "/client-api/api/token";

using (HttpClient client = new HttpClient())`enter code here`
{
    client.BaseAddress = new Uri(Baseurl);
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

    List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

    keyValues.Add(new KeyValuePair<string, string>("client_id", "5196810"));
    keyValues.Add(new KeyValuePair<string, string>("grant_type", "password"));
    keyValues.Add(new KeyValuePair<string, string>("username", "abc.a@gmail.com"));
    keyValues.Add(new KeyValuePair<string, string>("password", "Sonata@123"));
    keyValues.Add(new KeyValuePair<string, string>("platform", "FRPWeb"));


    HttpContent content = new FormUrlEncodedContent(keyValues);
    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    content.Headers.ContentType.CharSet = "UTF-8";

    var result = client.PostAsync(url, content).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
}
Run Code Online (Sandbox Code Playgroud)