0

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?

3
  • 1
    2 methods are fine, just use attribute routes to specify different urls. Are they the same URL? Commented Jan 18, 2016 at 5:36
  • They can be but they don't have to be. I'm trying to understand the best way to handle it. Commented Jan 18, 2016 at 15:38
  • You can use [ActionName(" ")] attribute Commented Feb 5, 2016 at 6:56

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Side note: for naming you'd be looking for /api/city/name (GET/POST) rather than include "post" in a url...
@AlexeiLevenkov Agreed!
-1

You can give the controller a route prefix

[RoutePrefix("Note")]
public class NoteController

then give a specific route to whatever action

[Route("", Name = "Note")]
[HttpGet]
public async Task<IHttpActionResult> Get (string tenantName, [FromBody] TagTdo entity)

[Route("", Name = "CreateNote")]
[HttpPost]        
public async Task<IHttpActionResult> Post (string tenantName, [FromBody] NoteDto entity)

[Route("Update\{id}", Name = "UpdateNote")]
[HttpPut]        
public async Task<IHttpActionResult> Put(string tenantName, [FromBody] NoteDto entity)

Then the route will be:

\Note [GET]
\Note [POST]
\Note\Update\4 [PUT]

Also as a naming convention DON'T use long name in the route, break into several words with slash and http verb

Don't use GetUserContacts, use User\Contacts [GET].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.