[Route("api/advertisement/{brandID}/{advertisementID}")]
public class BaseApiController : ApiController
{
public string AdvertisementID { get; private set; }
public int BrandID { get; private set; }
public BaseReportRepository ReportRepository { get; private set; }
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
var routeData = controllerContext.RouteData;
this.AdvertisementID = routeData.Values["advertisementID"].ToString();
this.BrandID = (int)routeData.Values["brandID"];
this.ReportRepository = RepositoryFactory
.CreateRepository(this.BrandID)
.ReportRepository;
}
}
为什么无法获取路由器数据brandID
答案 0 :(得分:1)
这样的事情可以解决你的问题:
IHttpRouteData requestRouteData = controllerContext.Request.GetRouteData();
IEnumerable<IHttpRouteData> subroutes = (IEnumerable<IHttpRouteData>)requestRouteData.Values["MS_SubRoutes"];
IHttpRouteData routeData = subroutes.FirstOrDefault();
if (routeData != null)
{
this.AdvertisementID = routeData.Values["advertisementID"].ToString();
this.BrandID = int.Parse(routeData.Values["brandID"].ToString());
}
您还应该限制brandID参数:
[Route("api/advertisement/{brandID:int}/{advertisementID}")]
如果您以任何方式遍历路径集合(例如在ControllerSelector中),了解这些路径的实际位置非常重要。使用属性路由时,所有路由属性都将添加到没有名称的公共路由中。这是一个特殊的路由,它是一个名为RouteCollectionRoute的内部类的实例。 此路由具有一组子路由,您可以查询这些子路由,其中包括 all 属性路由。