【问题标题】:Get a custom answer, an object for an HTTP Post request in a Web API获取自定义答案,即 Web API 中 HTTP Post 请求的对象
【发布时间】:2021-07-26 14:10:25
【问题描述】:

我称之为 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;
}

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

【问题讨论】:

  • result.Content.ReadAsStringAsync()
  • @JohnathanBarclay 我在答案中看到了我的 Guid。但是当我想像这样反序列化时 JsonSerializer.Deserialize(res);也不例外,但 Guid 是 0000-0000 ...有什么想法吗?
  • 你在result.Content.ReadAsStringAsync()的结果上使用await吗?
  • 如果您没有针对MyAnswer 使用自定义(反)序列化程序,那么await result.Content.ReadAsAsync&lt;MyAnswer&gt;() 将为您带来神奇的效果。

标签: c# .net asp.net-web-api httprequest


【解决方案1】:
    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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多