Sam Sam - 17 days ago 4
C# Question

ASP.NET API routing

I'm working on an ASP.NET 5 API and understand that, in order to make the API as "restful" as possible, we use Http verbs as method names.

My question is what happens if I have multiple methods that do different things and all have to be HttpPost?

Say, I have a method that I may call to update a user's first name and may have another method that I use to update the user's city. In both cases, the input parameters will be user ID (GUID) and value which is a string.

[HttpPost("id")]
public void Post([FromRoute]id, [FromBody]firstName)
{
// Change user's first name
}

[HttpPost("id")]
public void Post([FromRoute]id, [FromBody]city)
{
// Change user's city
}


How do I name my methods in this case?

Answer

To have 2 post methods that do different things, use the "ActionName" attribute.

[HttpPost("id")]
[ActionName("FirstNamePost")]
public void FirstNamePost([FromRoute]id, [FromBody]firstName)
{
   // Change user's first name
}

[HttpPost("id")]
[ActionName("CityPost")]
public void CityPost([FromRoute]id, [FromBody]city)
{
   // Change user's city
}

So you would call "www.mysite.com/api/citypost/1" or "www.mysite.com/api/FirstNamePost/1"

Another option would be to only have one post method and add a 3rd parameter to distinguish between a name update or city update.