Home > Software engineering >  Postman form-data works (WebAPI can parse 1) but raw data does not (WebAPI receives 0, instead of in
Postman form-data works (WebAPI can parse 1) but raw data does not (WebAPI receives 0, instead of in

Time:01-08

I am using Postman to test my .NET 6.0 WebAPI.

When I try to process a form-data request, the WebAPI gets the original value of "parameter" enter image description here

When I try to process a raw data request, the WebAPI gets the default value of "parameter"

enter image description here

This is the code of my .NET 6.0 controller:

[Route("[controller]")]
public class SiteInfoController : Controller

{
    [HttpGet]
    [AllowAnonymous]
    [Route("Test")]
    public IActionResult Test(int parameter)
    {
        return Ok($"response: {parameter}");
    }
}

I added in Headers

Content-Type application/json
Accept application/json

but it didn't help me Please help me to find the reason why form-data works (WebAPI can parse 1) but raw data does not (WebAPI receives 0, instead of initial 1) in .NET 6.0 WebAPI controller GET request.

enter image description here

CodePudding user response:

You are trying to read an object from the body of a request. You must define said object and tell the framework where to read it from. And HttpGet can't have a body. You must use HttpPost or any other verb that can handle it:

[Route("[controller]")]
public class SiteInfoController : Controller
{

    private sealed class MyParameter
    {
        public int Parameter { get; set; }
    }

    [HttpPost]
    [AllowAnonymous]
    [Route("Test")]
    public IActionResult Test([FromBody] MyParameter parameter)
    {
        return Ok($"response: {parameter.Parameter}");
    }
}

Make sure you change your PostMan script to use Post and not Get.

  • Related