Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to reach API using Content-Type application/x-www-form-urlencoded

I am building API restful server using dotnet core framework. I added my controller and trying to reach an endpoint using postman.

I have 2 problems

  • Problem 1

    // POST api/user
    [HttpPost]
    [Authorize()]
     public async Task<IActionResult> Post([FromBody]UserModel user)
    {
    }
    

Unless I send the request from postman as application/json by typing raw json, I can't reach this endpoint if I use application/x-www-form-urlencoded instead I always get 415 unsupported media type

  • Problem 2

    // POST api/user/avatar
    [HttpPost]
    [Authorize()]
    [Route("avatar")]
    public async Task<IActionResult> Post([FromBody]UserModel user, [FromBody]IFormFile file)
    {
    }
    

I don't know how to reach such an endpoint using postman

like image 795
mohamed elsabagh Avatar asked Feb 06 '23 00:02

mohamed elsabagh


2 Answers

In problem 1 you just need to use FromForm attribute instead of FromBody. As for second, i think will be easier write simple unit test or use Swashbuckle, it has great interface for such requests

like image 125
Joe Barkley Avatar answered Feb 08 '23 15:02

Joe Barkley


You can use Consumes attribute like that:

// POST api/user
[HttpPost, Consumes("application/x-www-form-urlencoded")]
[Authorize()]
public async Task<IActionResult> Post([FromBody]UserModel user)
{
}
like image 24
Sydd Avatar answered Feb 08 '23 15:02

Sydd