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

后端 未结 3 1363
伪装坚强ぢ
伪装坚强ぢ 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: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;
    }
    

提交回复
热议问题