WebAPI .NET - POST request filter by parameters

和自甴很熟 提交于 2019-12-13 04:26:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!