(400) Bad Request when trying to post simple value to an API

后端 未结 3 1365
伪装坚强ぢ
伪装坚强ぢ 2020-12-11 19:54

I have this LoansController for a web api

[Route(\"api/[controller]\")]
[ApiController]
public class LoansController : ControllerBase
{
    // G         


        
3条回答
  •  Happy的楠姐
    2020-12-11 20:06

    Reason

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

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

    Here a plain string is a sequence of characters which is quoted by "". In other words, to represent the string, you need include the quotes before and after these characters when sending request to this action method.

    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'}"
    

    Note : We have to use doublequoted string ! Don't send string without the ""

    How to fix

    1. To send a plain string, simply use the following PowerShell scripts :

      $postParams = "{'value':'123'}"
      $postParams = '"'+$postParams +'"'
      Invoke-WebRequest http://localhost:1113/api/loans -Body $postParams  -Method Post  -ContentType 'application/json'
      
    2. Or if you would like to send the payload with json, you could create a DTO to hold the value property:

      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;
      }
      

      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.

提交回复
热议问题