Is there a reason why each Web API action needs to be decorated with e.g.
[AcceptVerbs("Get", "Post")]
to specifically accept Get and Post? Is there a way to globally allow all verbs for all actions and not relying on Get or Post Prefeix of the method name instead?
As much as there is the rest way of doing things, to bound verbs to Actions, why not allow all just restrict them when needed?
The reason for not enabling that by default is that it would break your RESTful api.
If you enabled all verbs by default then it would be impossible to identify which action to be used.
Let's take an example, you have a UsersController
which contains 4 methods: Get all users
, Get specific user
, Post user
and Delete user
. These methods will only result in two different endpoints, and for the WebApi engine to be able to select the correct method it needs the HTTP verb.
UsersController
[RoutePrefix("api/users")]
public class UsersApiController : ApiController
{
[Route("")]
public IHttpActionResult Get()
{
var result = _userRepository.GetAll();
return Ok(result);
}
[Route("{id:guid}")]
public IHttpActionResult Get(Guid id)
{
var result = _userRepository.GetById(id);
if (result == null)
return NotFound();
return Ok(result);
}
[Route("")]
public IHttpActionResult Post([FromBody]UserPostModel model)
{
var user = new User(model.FirstName, model.LastName);
_userRepository.Add(user);
return Created<User>(Request.RequestUri + user.Id.ToString(), user);
}
[Route("{id:guid}")]
public IHttpActionResult Delete(Guid id)
{
var result = _userRepository.Delete(id);
if (!result)
return BadRequest();
return Ok();
}
public class UserPostModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class User
{
public User(string firstName, string LastName)
{
Id = Guid.NewGuid();
FirstName = firstName;
LastName = lastName;
}
public Guid Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
}
}