Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The requested resource does not support HTTP method GET

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 }
            );
like image 825
Elisabeth Avatar asked Jan 09 '14 19:01

Elisabeth


1 Answers

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."

like image 105
Mister Epic Avatar answered Nov 15 '22 11:11

Mister Epic