(400)尝试将简单值发布到API时出现错误请求

编程入门 行业动态 更新时间:2024-10-25 23:28:47
本文介绍了(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 localhost:1113/api/loans -Body $postParams -Method Get

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

and it works fine (I get value1 and value2)

但是当我尝试

$postParams = "{'value':'123'}" Invoke-WebRequest 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 localhost:1113/api/loans HTTP/1.1 Content-Type: application/json "{'value':'123'}"

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

如何修复

  • 要发送纯字符串,只需使用以下 PowerShell 脚本: $postParams = "{'value':'123'}" $postParams = '"'+$postParams +'"' Invoke-WebRequest 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 localhost:1113/api/loans -Body $postParams -Method Post -ContentType 'application/json'

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

    These two approaches both work flawlessly for me.

    更多推荐

    (400)尝试将简单值发布到API时出现错误请求

    本文发布于:2023-10-10 22:29:27,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1479933.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:出现错误   简单   API

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!