问题
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.
回答1:
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
}
}
回答2:
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()
{}
来源:https://stackoverflow.com/questions/57090748/webapi-net-post-request-filter-by-parameters