(400)尝试将简单值发布到API时出现错误请求 [英] (400) Bad Request when trying to post simple value to an API

查看:89
本文介绍了(400)尝试将简单值发布到API时出现错误请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于Web API的 LoansController

I have this LoansController for a web api

[Route("api/[controller]")]
[ApiController]
public class LoansController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // POST api/loans
    [HttpPost]
    public void Post([FromBody] string value)
    {

    }
}

在PowerShell中,我可以致电

In PowerShell I can call

Invoke-WebRequest http://localhost:1113/api/loans -Body $postParams -Method Get

,它工作正常(我得到 value1 value2 )

and it works fine (I get value1 and value2)

但是当我尝试

$postParams = "{'value':'123'}"
Invoke-WebRequest http://localhost:1113/api/loans -Body $postParams -Method Post # -ContentType 'Application/json'

我一直都在获得

Invoke-WebRequest:远程服务器返回错误:(400)错误的请求.

Invoke-WebRequest : The remote server returned an error: (400) Bad Request.

我在做什么错了?

我尝试添加 -ContentType'Application/json',但没有区别

I tried adding -ContentType 'Application/json' but it made no difference

我想念什么?

我也尝试了 Invoke-RestMethod ,但结果相同.

I also tried Invoke-RestMethod but with the same results..

接下来,我从 value 参数中删除了 [FromBody] ,但是 value 现在以 null 的形式出现>

Next I removed [FromBody] from the value param but value now comes in as null

推荐答案

原因

这只是发生,因为您的操作方法期望HTTP请求的正文中出现简单的 string :

It just happens because your action method is expecting a plain string from HTTP request's Body:

[HttpPost]
public void Post([FromBody] string value)
{

}

这里的普通字符串是由" 引用的一系列字符.换句话说,要表示字符串,在向此操作方法发送请求时,您需要在这些字符之前和之后加引号.

如果您确实希望将json字符串 {'value':'123'} 发送到服务器,则应使用以下有效负载:

If you do want to send the json string {'value':'123'} to server, you should use the following payload :

POST http://localhost:1113/api/loans HTTP/1.1
Content-Type: application/json

"{'value':'123'}"

注意:我们必须使用双引号字符串!没有"

如何修复

  1. 要发送纯字符串,只需使用以下 PowerShell 脚本:

$postParams = "{'value':'123'}"
$postParams = '"'+$postParams +'"'
Invoke-WebRequest http://localhost:1113/api/loans -Body $postParams  -Method Post  -ContentType 'application/json'

  • 或者,如果您想使用json发送有效载荷,则可以创建一个 DTO 来保存 value 属性:

    public class Dto{
        public string Value {get;set;}
    }
    

    并将您的操作方法更改为:

    and change your action method to be :

    [HttpPost]
    public void Post(Dto dto)
    {
        var value=dto.Value;
    }
    

    最后,您可以调用以下 PowerShell 脚本来发送请求:

    Finally, you can invoke the following PowerShell scripts to send request :

    $postParams = '{"value":"123"}'
    Invoke-WebRequest http://localhost:1113/api/loans -Body $postParams  -Method Post  -ContentType 'application/json'
    

  • 这两种方法对我来说都完美无缺.

    These two approaches both work flawlessly for me.

    这篇关于(400)尝试将简单值发布到API时出现错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆