WebAPI .NET - POST request filter by parameters

340 Views Asked by At

I use POST to create messages and to update them (I need to use POST, not PUT). The API has the following instructions:

POST /api/message

POST /api/message?update_message

How can I difference between both? Guess I have to do an if in the function:

[HttpPost]
[Route("api/message")]
public async Task<HttpResponseMessage> Handle()
{}

checking if the request contains the parameter update_message.

Any idea on how to solve that? Thanks.

2

There are 2 best solutions below

0
Iñigo On BEST ANSWER

Finally solved with both actions separated with this syntax:

For POST /api/message?update_message=true requests:

[HttpPost]
[Route("api/message")]
public async Task<HttpResponseMessage> Update(bool update_message, [FromBody] message m)
{}

For POST /api/message requests:

[HttpPost]
[Route("api/message")]
public async Task<HttpResponseMessage> Create()
{}
0
Lorenzo Isidori On

A query string parameter has a key and a value. You should add a value to your "update_message" param and use it to decide if create or update a message. In the route attribute you are able to define the query string param.

[HttpPost, Route("api/message/{update_message=update_message}")]
public async Task<HttpResponseMessage> Handle(string update_message)
{
     if(string.Equals("true", update_message)
     { 
          // update
     }
     else
     {
         //create
     }  
}