When I run this url: /api/users/1
it does only map to the Delete action when I use the HttpDelete-Attribute. What is the reason for this behavior?
Else I get his message: The requested resource does not support HTTP method GET
[RoutePrefix("api/users")]
public class UserController : ApiController
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[Route("")]
public HttpResponseMessage Get()
{
return Request.CreateResponse<IEnumerable<UserDTO>>(HttpStatusCode.OK, _userService.GetUsers());
}
[Route("{id:int}")]
[HttpDelete]
public HttpResponseMessage Delete(int id)
{
_userService.Delete(id);
return Request.CreateResponse(HttpStatusCode.OK, "User was deleted successfully");
}
}
These are my routes:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", action = "Start", id = RouteParameter.Optional }
);
By convention, HTTP verbs will match to an action name that is prefixed with that HTTP verb.
So, it's complaining you don't have an action for an HTTP GET, which is the verb used when you make a simple request with your browser. You need an action named something like:
public HttpResponseMessage Get(int id)
or even
public HttpResponseMessage GetUser(int id)
Obviously if you make a request with DELETE, it will map to the Delete action you have defined.
Ref: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
"To find the action, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with "Get...", such as "GetContact" or "GetAllContacts". This convention applies only to GET, POST, PUT, and DELETE methods. You can enable other HTTP methods by using attributes on your controller. We’ll see an example of that later."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With