属性路由不起作用

时间:2017-11-16 14:33:06

标签: c# asp.net asp.net-web-api asp.net-mvc-routing

我在2013年的visual studio express中创建了一个rest api。

我有2个控制器:一个用于订单,一个用于客户。

我已经创建了以下内容:

/api/clients获取有关所有客户的信息

/api/clients/1获取有关id = 1

的客户的信息

/api/orders/10获取有关id = 10

的订单的信息

现在,我想创建这个:

/api/clients/1/orders - 获取有关身份1

的所有客户订单的信息

我已阅读有关属性路由的信息,但我无法使其正常工作。

OrdersController.cs

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
    public Order Get(string id)
    {
        // ...
    }

    [Route("clients/{id}/orders")]
    public List<Order> GetByClient(string id)
    {
        // ...
    }
}

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Enable CORS
        config.EnableCors();

        //config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

像这样,所有其他请求都能正常运行,但当我尝试访问/api/clients/1/orders时,我收到错误HTTP Error 404.0 - Not Found. The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

但是,一旦我取消注释config.MapHttpAttributeRoutes();,我就无法再访问任何请求了 - 他们都会返回此信息:

<Error>
    <Message>An error has occurred.</Message>
<ExceptionMessage>
    The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
    at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>
</Error>

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

使用路由属性[Route("clients/{id}/orders")],您应该不是GetByClient()网址,而是/api/clients/1/orders访问操作/clients/1/orders。要拥有原始网址,只需修复路由:

[Route("api/clients/{id}/orders")]
public List<Order> GetByClient(string id)

答案 1 :(得分:2)

取消注释您的config.MapHttpAttributeRoutes()行,然后在您的Global.asax文件中替换它:

WebApiConfig.Register(GlobalConfiguration.Configuration);

用这个:

GlobalConfiguration.Configure(WebApiConfig.Register);

你可以在这里阅读:

Attribute Routing in ASP.NET Web API 2