0

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>
4

1 回答 1

2

根据您的错误描述,您似乎在调用 MapHttpAttributeRoutes 之前已经注册了常规路由。例如,您可能有一条类似config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}"...). 在这种情况下,请求 likeapi/user/someid将匹配此路由,并且 Web API 将寻找 type 的控制器UserControllerMapHttpAttributeRoutes确保在这条常规路线之前致电。

基本规则:更具体的路由应该在不太具体或通用的路由之前注册。

于 2014-01-10T23:28:34.913 回答