微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net 核心对 http GET 和发送正文的错误请求

如何解决.net 核心对 http GET 和发送正文的错误请求

我正在尝试发送 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;
};

解决方法

因为数据格式是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();
 //...

另外,确保后端被对象接收。

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

和模型

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

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。