首页 > 解决方案 > 获取自定义答案,即 Web API 中 HTTP Post 请求的对象

问题描述

我将此 WebApi 端点称为:

public IActionResult MyEndPoint([FromBody] MyType myType)
{
    // I do some stuff

    var answer = new MyAnswer { Id = Guid.NewGuid() };

    return Ok(answer);
}

调用端点的调用是这样的:

public async Task<string> httpPost(string url, string content)
{
    var response = string.Empty;
    using(var client = new HttpClient())
    {
        HttpRequestMessage request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri(url),
            Content = new StringContent(content, Encoding.UTF8, "application/json")
        };

        HttpResponseMessage result = await client.SendAsync(request);
        if(result.IsSuccessStatusCode)
        {
            response = result.StatusCode.ToString(); //here
        }
    }
    return response;
}

我想访问 MyAnswer 对象返回的 Ok() //here 所在的位置。我放了一个断点,但没有任何东西看起来像我的对象。

标签: c#.netasp.net-web-apihttprequest

解决方案


    public async Task<MyAnswer> HttpPost(string url, string content)
    {
        var response = new MyAnswer();
        using (var client = new HttpClient())
        {
            HttpRequestMessage request = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(url),
                Content = new StringContent(JsonSerializer.Serialize(content), Encoding.UTF8, "application/json")
            };

            HttpResponseMessage result = await client.SendAsync(request);
            if (result.IsSuccessStatusCode)
            {
                var responseString = await result.Content.ReadAsStringAsync();
                response =  JsonSerializer.Deserialize<MyAnswer>(responseString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            }
        }
        return response;
    }

推荐阅读