问题描述
我有很少的控制器继承自同一个基类。在他们不相互分享的不同行动中,他们确实有一些完全相同。我希望在我的基类上有这些,因为它们完全相同,只是通过不同的路径访问它们。
I have few controllers that inherit from the same base class. Among the different actions that they don't share with each other, they do have a few that are completely identical. I would like to have these on my base class because they all work completely the same it's just that they're accessed through different routes.
我应该如何定义这些行为有几种不同的路线?
我继承的类也设置了 RoutePrefixAttribute
他们每个人都指向不同的路线。
My inherited classes also have a RoutePrefixAttribute
set on them so each of them is pointing to a different route.
我有一个名为<$ c的基本抽象类$ c> Vehicle 然后继承 Car
, Bike
,巴士
等等所有人都有共同的行动 Move()
I have base abstract class called Vehicle
and then inherited Car
, Bike
, Bus
etc. All of them would have common action Move()
/bus/move
/car/move
/bike/move
如何在我的基类 Vehicle
上定义动作 Move()
以便它将是在每个子类路由上执行?
How can I define action Move()
on my base class Vehicle
so that it will be executed on each subclass route?
推荐答案
检查我在这里给出的答案,它引用了这篇文章的答案 .NET WebAPI属性路由和继承
Check the answer I gave here WebApi2 attribute routing inherited controllers, which references the answer from this post .NET WebAPI Attribute Routing and inheritance
您需要做的是覆盖 DefaultDirectRoutePrivider
:
What you need to do is overwrite the 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配置
With that done you then need to configure it in your web api configuration
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
.....
// Attribute routing. (with inheritance)
config.MapHttpAttributeRoutes(new WebApiCustomDirectRouteProvider());
....
}
}
然后你会能够做你所描述的这样的
You will then be able to do what you described like this
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() {
...
}
}
这篇关于WebAPI控制器继承和属性路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!