Rob*_*nik 9 c# asp.net inheritance asp.net-web-api-routing asp.net-web-api2
我有很少的控制器继承自相同的基类.在他们不相互分享的不同行为中,他们确实有一些完全相同.我希望在我的基类上有这些,因为它们都完全相同,只是它们通过不同的路径访问.
我应该如何用几种不同的路线定义这些行为?
我继承的类也有一个RoutePrefixAttribute集合,所以每个类都指向不同的路由.
我有一个叫做抽象基类Vehicle,然后继承Car,Bike,Bus等所有的问题都有共同行动Move()
/bus/move
/car/move
/bike/move
Run Code Online (Sandbox Code Playgroud)
如何Move()在我的基类上定义操作,Vehicle以便在每个子类路由上执行?
Nko*_*osi 14
检查我在这里给出的答案WebApi2属性路由继承控制器,它引用了这篇文章的答案.NET WebAPI属性路由和继承
你需要做的是覆盖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);
}
}
Run Code Online (Sandbox Code Playgroud)
完成后,您需要在web api配置中进行配置
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
.....
// Attribute routing. (with inheritance)
config.MapHttpAttributeRoutes(new WebApiCustomDirectRouteProvider());
....
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您就可以按照这样的描述进行操作
public abstract class VehicleControllerBase : ApiController {
[Route("move")] //All inheriting classes will now have a `{controller}/move` route
public virtual HttpResponseMessage Move() {
...
}
}
[RoutePrefix("car")] // will have a `car/move` route
public class CarController : VehicleControllerBase {
public virtual HttpResponseMessage CarSpecificAction() {
...
}
}
[RoutePrefix("bike")] // will have a `bike/move` route
public class BikeController : VehicleControllerBase {
public virtual HttpResponseMessage BikeSpecificAction() {
...
}
}
[RoutePrefix("bus")] // will have a `bus/move` route
public class BusController : VehicleControllerBase {
public virtual HttpResponseMessage BusSpecificAction() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4168 次 |
| 最近记录: |