Question

I'm using attribute routing to specify my routes in a controller that inherits from System.Web.Http.ApiController. I'm getting some funky behavior. Here's some sample code:

[RoutePrefix("api/1/user")]
public class UserRestController : ApiController
{
    UserService userService = new UserService();

    [Route("{id}"), HttpGet]
    public UserDTO Get(string id)
    {
        var user = userService.GetUserById(id);

        return user;
    }
}

That works absolutely how I would expect. When I visit ~/api/1/user/someId I get the expected information back. When I switch to not include the '1' in the route prefix I get "No HTTP resource was found that matches the request URI 'baseUrl/api/user/someId'."

I have mvc routes, web api routes and attribute routes all being registered on app start in this project but I would think that the default routes for this controller would be ~/userrest/... so I wouldn't think registering those would be the cause of this but I could be wrong.

Sample of what I want:

[RoutePrefix("api/user")]
public class UserRestController : ApiController
{
    UserService userService = new UserService();

    [Route("{id}"), HttpGet]
    public UserDTO Get(string id)
    {
        var user = userService.GetUserById(id);

        return user;
    }
}

I'd expect that ~/api/user/someId would work however I get the error mentioned above ("No HTTP resource was found that matches the request URI 'baseUrl/api/user/someId'.").

Full error xml:

<Error> 
    <Message> 
        No HTTP resource was found that matches the request URI     
        'baseUrl/api/user/someId';. 
    </Message> 
    <MessageDetail> 
        No type was found that matches the controller named 'user'. 
    </MessageDetail> 
</Error>
Was it helpful?

Solution

Based on your error description, you seem to have registered conventional routes before calling MapHttpAttributeRoutes. For example, you might be having a route like config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}"...). In this case the request like api/user/someid would match this route and the Web API would be looking for a controller of type UserController. Make sure to call MapHttpAttributeRoutes before this conventional route.

Basic rule: more specific routes should be registered before less-specific or generic routes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top