【问题标题】:.net core bad request for http GET and sending body.net 核心对 http GET 和发送正文的错误请求
【发布时间】:2021-03-15 12:24:12
【问题描述】:

我正在尝试发送 http GET 请求,但我收到 400 BadRequest。 我只需要有人确认我正确打包了请求。 我认为我的内容不好?

var um = "123456";
var request = new HttpRequestMessage
{
    Method = HttpMethod.Get,
    RequestUri = new Uri($"{_iOptions.Server}{_iOptions.Method.GetData}")
};

request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes("{ \"um\": " + um + " }"));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var responseMessage = await _httpClient.SendAsync(request).ConfigureAwait(false);
responseMessage.EnsureSuccessStatusCode();

GetResponse response = await responseMessage.Content.ReadAsAsync<GetResponse>();

if (response.Code == (int)System.Net.HttpStatusCode.OK)
{
    response.Success = true;
    return response;
}
else
{
    response.Success = false;
    return response;
};

【问题讨论】:

  • Bad Request 表示内容不符合 API 的要求。在不知道您的 API 的详细信息的情况下,我们只能猜测。我的猜测是您将 json 作为字节数组内容而不是字符串内容发送。
  • 我知道@Crowcoder,但我没有这个 api 的任何详细规格。我会尝试作为 stringContent 发送,我会告诉你的。谢谢。
  • 如果您使用的是 HTTP(不是 HTTPS),您可以使用像 wireshark 或 fiddler 这样的嗅探器来查看请求。
  • 您确定是Encoding.UTF8.GetBytes("{ \"um\": " + um + " }") 而不是Encoding.UTF8.GetBytes("{ \"um\": \"" + um + "\" }") 吗?
  • @Crowcoder -- 使用ByteArrayContent 是完全可以接受的。我一直用它来发送 JSON。 StringContent 实际上是从 ByteArrayContent 派生的。看看the source

标签: c# asp.net-core .net-core get httpclient


【解决方案1】:

因为数据格式是application/json,所以必须使用HttpMethod.Post。并且值应该在(Encoding.UTF8.GetBytes("{ \"um\": \"" + um + "\" }") 中添加双引号

var client = new HttpClient();
var um = "123456";
var request = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri("https://localhost:...")
        };

 request.Content = new ByteArrayContent(Encoding.UTF8.GetBytes("{ \"um\": \"" + um + "\" }"));
 request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

 var responseMessage = await client.SendAsync(request).ConfigureAwait(false);
 responseMessage.EnsureSuccessStatusCode();
 //...

另外,确保后端是由object接收的。

    [HttpPost]
    public IActionResult get([FromBody]MyModel myModel)
    {
        return Ok(myModel.um);
    }

还有模特

public class MyModel
{
    public string um { get; set; }
}

【讨论】:

  • @Stefan0309,你能接受这个答案,还是有其他问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2022-01-25
  • 2023-03-18
  • 2020-04-25
相关资源
最近更新 更多