Generics Web API。具有属性路由的通用控制器
问题 当我在实际控制器上创建带有路由的方法时,请说: “api/国家/某物” 当我执行上述请求时,我的代码被执行,数据被返回 但当我尝试在基地控制器上呼叫我的路线时。例如:“api/country/code/123” 我得到一个404错误 问题 如何在使用属性路由的同时实现通用路由 特定控制器Generics Web API。具有属性路由的通用控制器,generics,asp.net-web-api,routing,owin,attributerouting,Generics,Asp.net Web Api,Routing,Owin,Attributerouting,问题 当我在实际控制器上创建带有路由的方法时,请说: “api/国家/某物” 当我执行上述请求时,我的代码被执行,数据被返回 但当我尝试在基地控制器上呼叫我的路线时。例如:“api/country/code/123” 我得到一个404错误 问题 如何在使用属性路由的同时实现通用路由 特定控制器 [RoutePrefix("Country")] public class CountryController : MasterDataControllerBase<Country, Count
[RoutePrefix("Country")]
public class CountryController : MasterDataControllerBase<Country, CountryDto>
{
public CountryController(
IGenericRepository<Country> repository,
IMappingService mapper,
ISecurityService security) : base(repository, mapper, security)
{
}
}
[RoutePrefix(“国家”)]
公共类CountryController:MasterDataControllerBase
{
公共财务总监(
IGenericRepository存储库,
IMappingService映射器,
ISecurityService安全性):基础(存储库、映射器、安全性)
{
}
}
基础
public class MasterDataControllerBase<TEntity, TEntityDto> : ControllerBase
where TEntity : class, ICodedEntity, new()
where TEntityDto : class, new()
{
private readonly IMappingService mapper;
private readonly IGenericRepository<TEntity> repository;
private readonly ISecurityService security;
public MasterDataControllerBase(IGenericRepository<TEntity> repository, IMappingService mapper, ISecurityService security)
{
this.security = security;
this.mapper = mapper;
this.repository = repository;
}
[Route("code/{code}")]
public TEntityDto Get(string code)
{
this.security.Enforce(AccessRight.CanAccessMasterData);
var result = this.repository.FindOne(o => o.Code == code);
return this.mapper.Map<TEntity, TEntityDto>(result);
}
}
公共类MasterDataControllerBase:ControllerBase
其中tenty:class,ICodedEntity,new()
其中TEntityDto:class,new()
{
专用只读IMappingService映射器;
专用只读IGenericRepository存储库;
私有只读ISecurityService安全性;
公共MasterDataControllerBase(IGenericRepository存储库、IMappingService映射器、iSecurity服务安全)
{
安全=安全;
this.mapper=mapper;
this.repository=存储库;
}
[路线(“代码/{code}”)]
要获取的公共TentityData(字符串代码)
{
this.security.Enforce(AccessRight.CanAccessMasterData);
var result=this.repository.FindOne(o=>o.Code==Code);
返回此.mapper.Map(结果);
}
}
Web API中的属性路由不支持继承路由
属性。如果查看RouteAttribute
类的定义,则可以通过Inherited=false
看到这一点
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class RouteAttribute : Attribute, IDirectRouteFactory, IHttpRouteInfoProvider
{ ...
这解释了当Route
属性有效地消失时,为什么会得到404
由于属性是不可继承的,并且类是密封的,所以我不知道是否有一种方法可以使用现成的属性路由基础设施来实现这一点
更新:WebAPI团队的一名成员解释说,这是一个设计决策,它不是继承的 可能与Web API 2.2重复,因为可以继承路由属性。看见