1 回答
TA贡献1846条经验 获得超7个赞
您需要做的是覆盖DefaultDirectRoutePrivider以允许路由继承:
public class WebApiCustomDirectRouteProvider : DefaultDirectRouteProvider {
protected override IReadOnlyList<IDirectRouteFactory>
GetActionRouteFactories(HttpActionDescriptor actionDescriptor) {
// inherit route attributes decorated on base class controller's actions
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
}
}
完成后,您将需要在您的 web api 配置中配置它以及自定义路由约束
public static void Register(HttpConfiguration config) {
var constraintResolver = new DefaultInlineConstraintResolver() {
ConstraintMap = {["apiVersion"] = typeof(ApiVersionRouteConstraint)}
};
var directRouteProvider = new WebApiCustomDirectRouteProvider();
// Attribute routing. (with inheritance)
config.MapHttpAttributeRoutes(constraintResolver, directRouteProvider);
config.AddApiVersioning(_ => { _.AssumeDefaultVersionWhenUnspecified = true; });
}
所以现在继承值控制器现在将具有派生控制器中可用的基本路由
用于演示目的
[ApiVersion("1.0")]
[RoutePrefix("api/v{version:apiVersion}/Values")]
[ControllerName("Values")]
public class ValuesController : ApiController {
[HttpGet]
[Route("")] // GET api/v1.0/values
public virtual IHttpActionResult Get() {
return Ok(new string[] { "value1", "value2" });
}
[HttpGet]
[Route("{id:int}")] // GET api/v1.0/values/5
public virtual IHttpActionResult Get(int id) {
return Ok("value from 1");
}
}
[ApiVersion("2.0")]
[RoutePrefix("api/v{version:apiVersion}/Values")]
[ControllerName("Values")]
public class Values2Controller : ValuesController {
//Will have inherited GET "api/v2.0/Values" route
// GET api/v2.0/values/5 (Route also inherited from base controller)
public override IHttpActionResult Get(int id) {
return Ok("value from 2");
}
}
您会注意到子级中的路由并未用于覆盖的操作,因为它也将从基本控制器继承。
- 1 回答
- 0 关注
- 180 浏览
添加回答
举报