【问题标题】:ASP.NET WebAPI Routing IssueASP.NET WebAPI 路由问题
【发布时间】:2013-07-03 15:22:23
【问题描述】:

假设我有以下动作;

// api/products
public IEnumerable<ProductDto> GetProducts()
public ProductDto GetProduct(int id)

// api/products/{productId}/covers
public IEnumerable<CoverDto> GetCovers(int productId)

创建路径以用作“主”产品的快捷方式的最佳方法是什么?api/products/master

我尝试添加一个主控制器,并将上面的内容路由到它,但我收到以下错误:

The parameters dictionary contains a null entry for parameter 'id' 
of non-nullable type 'System.Int32' for method 'ProductDto GetProduct(Int32)' 
in 'ProductsController'. An optional parameter must be a reference type, 
a nullable type, or be declared as an optional parameter.

为了解决这个问题,我尝试将正常的产品路线更新为api/products/{id:int},但无济于事。

我想得到以下结果;唯一的区别是“主”产品将通过 code 而不是 id

获得
api/products
api/products/1
api/products/1/covers
api/products/master
api/products/master/covers

【问题讨论】:

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


    【解决方案1】:

    这些路线应该可以解决问题:

    config.Routes.MapHttpRoute(
        name: "MasterAction",
        routeTemplate: "api/{controller}/master/{action}",
        defaults: new { action = "GetProduct", id = 999 } // or whatever your master id is
    );
    
    config.Routes.MapHttpRoute(
        name: "Action",
        routeTemplate: "api/{controller}/{id}/{action}",
        defaults: new { action = "GetProduct" }
    );
    
    config.Routes.MapHttpRoute(
        name: "Default",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    您需要将GetCovers 方法的参数名称从productId 更改为id,或者您需要添加更多定义{productId} 的路由。

    使用“覆盖”路由,您需要将 URI 更改为:

    api/products/1/getcovers
    api/products/master/getcovers
    

    或者,如果您想保持 URI 不变,则需要将您的操作方法更改为如下所示

    [HttpGet]
    public IEnumerable<CoverDto> Covers(int id)
    

    【讨论】:

    • 谢谢,但就像我说的,“主”产品需要通过产品代码获得,而不是像您那样的 999 id。这将意味着另一个控制器操作,但我不知道如何执行路由。
    • 我想我不知道您所说的产品代码是什么意思。什么是产品代码示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多