Search code examples
asp.net-corehttp-postasp.net-core-webapi

How to fix the Validation Error from HTTP Post method


I have created a project using default web api template code for asp.net core 5 <TargetFramework>net5.0</TargetFramework> Then I added a method to test a post request in the WeatherForecastController

[HttpPost]
 public ActionResult<string> PostMethod([FromBody]string jsonString)
 {            
     return Ok(jsonString);
 }

If I remove the[FromBody] the code works fine. If I add [FromBody] and type something in the body like asdfasdf from swagger, it fails with 400 status error

{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "One or more validation errors occurred.", "status": 400, "traceId": "00-78bd11a5cea5244998ade80c059479d0-8cb569e070ca0047-00", "errors": { "$": [ "'a' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0." ] } }

Not able to figure out what the issue is! Could someone explain what causes this and would be great if you can point me to some resource that helps me understand how this validation is done. There was no data annotations done here with this simple code.

Body in Swagger!! :) enter image description here

Thanks in advance Murthy


Solution

  • Your body is not a string type,please add "",change it to

    "xxxxx"
    

    Test Result: enter image description here