如何在WebApi中继承控制器类级别的路由前缀? [英] How do you inherit route prefixes at the controller class level in WebApi?

查看:183
本文介绍了如何在WebApi中继承控制器类级别的路由前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意,我已经阅读了新的路由功能作为WebApi 2.2的一部分,以允许继承路由。但是,这似乎并没有解决我的特定问题。它似乎解决了继承动作级别路由属性的问题,但没有解决在类级别定义的路由前缀。
http:// www。 asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22#ARI

Note, I've read about the new routing features as part of WebApi 2.2 to allow for inheritance of routes. This does not seem to solve my particular issue, however. It seems to solve the issue of inheriting action level route attributes, but not route prefixes defined at the class level. http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-22#ARI

我想要做这样的事情:

[RoutePrefix("account")]
public abstract class AccountControllerBase : ControllerBase { }

[RoutePrefix("facebook")]
public class FacebookController : AccountControllerBase
{
    [Route("foo")]
    public async Task<string> GetAsync() { ... }
}

[RoutePrefix("google")]
public class GoogleController : AccountControllerBase
{
    [Route("bar")]
    public async Task<string> GetAsync() { ... }
}

我想 account 要继承的路由前缀,因此在定义Facebook和Google控制器时,我会获得路由:

I would like the account route prefix to be inherited, so when defining the Facebook and Google controllers, I get routes:

~/account/facebook/foo
~/account/google/bar

目前,路由的定义没有来自基类的帐户部分。

Currently, routes are getting defined without the account portion from the base class.

推荐答案

我有类似的要求。我做的是:

I had a similar requirement. What i did was:

public class CustomDirectRouteProvider : DefaultDirectRouteProvider
{
    protected override string GetRoutePrefix(HttpControllerDescriptor controllerDescriptor)
    {
        var routePrefix =  base.GetRoutePrefix(controllerDescriptor);
        var controllerBaseType = controllerDescriptor.ControllerType.BaseType;

        if (controllerBaseType == typeof(BaseController))
        {
            //TODO: Check for extra slashes
            routePrefix = "api/{tenantid}/" + routePrefix;
        }

        return routePrefix;
    }
}

其中 BaseController 是定义前缀的那个。现在普通的前缀工作,您可以添加自己的前缀。配置路由时,请调用

Where BaseController is the one defining what is the prefix. Now normal prefixes work and you can add your own. When configuring routes, call

config.MapHttpAttributeRoutes(new CustomDirectRouteProvider());

这篇关于如何在WebApi中继承控制器类级别的路由前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆