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

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


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.1Content-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.


Try to add headers

$url = 'http://localhost:1113/api/loans'$head = @{'ContentType'='Application/json'}Invoke-WebRequest -Uri $url -Body $postParams -Method Post -Headers $head 


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

$postParams = @{ "value": "123"} | ConvertTo-JsonInvoke-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;}