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

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

I have this LoansController for a web api

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


        
相关标签:
3条回答
  • 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.

    0 讨论(0)
  • 2020-12-11 20:22

    Try to add headers

    $url = 'http://localhost:1113/api/loans'
    $head = @{'ContentType'='Application/json'}
    Invoke-WebRequest -Uri $url -Body $postParams -Method Post -Headers $head 
    
    0 讨论(0)
  • 2020-12-11 20:22

    First, try using ConvertTo-Json in the powershell command:

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

    If it still doesn't work I suggest creating a model (data transfer object) and using model binding to bind your string value. Edit the controller Post method as below:

    public class MyModelDto {
        public string Value { get; set; }
    }
    
    // POST api/loans
    [HttpPost]
    public void Post([FromBody] MyModelDto model)
    {
        string value = model.Value;
    }
    
    0 讨论(0)
提交回复
热议问题