ASP.NET WebAPI路由问题

本文关键字:问题 路由 WebAPI NET ASP | 更新日期: 2023-09-27 18:21:24

假设我有以下操作;

// 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},但没有成功。

我想以以下内容结束发言;其中唯一的区别是"主"产品将通过代码获得,而不是id

api/products
api/products/1
api/products/1/covers
api/products/master
api/products/master/covers

ASP.NET WebAPI路由问题

这些路由应该起作用:

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)