【问题标题】:How to determine Route Prefix programmatically in asp.net mvc?如何在 asp.net mvc 中以编程方式确定路由前缀?
【发布时间】:2015-05-16 17:26:53
【问题描述】:

我想为我的公共/匿名控制器和来自管理员/经过身份验证的控制器和视图的视图提供一些 URL 分离。所以我最终完全使用了Attribute Routing,以便更好地控制我的网址。我希望我的公共 URL 以“~/Admin/etc”开头。而我的公共 URL 不会有任何这样的前缀。

公共控制器(几个之一)

[RoutePrefix("Home")]
public class HomeController : Controller
{
    [Route("Index")]
    public ActionResult Index()
    { //etc. }
}

管理控制器(几个之一)

[RoutePrefix("Admin/People")]
public class PeopleController : Controller
{
    [Route("Index")]
    public ActionResult Index()
    { //etc. }
}

这允许我拥有公共 URL,例如:

http://myapp/home/someaction

...和管理员/经过身份验证的 URL,例如:

http://myapp/admin/people/someaction

但是现在我想根据用户是在站点的管理部分还是公共部分在视图中做一些动态的事情。如何以编程方式正确访问它?

我知道我可以做类似的事情

if (Request.Url.LocalPath.StartsWith("/Admin"))

...但它感觉“hacky”。我知道我可以通过

访问控制器和操作名称
HttpContext.Current.Request.RequestContext.RouteData.Values

...但是“admin”部分并没有反映在那里,因为它只是一个路由前缀,而不是实际的控制器名称。

那么,基本问题是,我如何以编程方式确定当前加载的视图是否在“admin”部分下?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing attributerouting


    【解决方案1】:

    你只需要从Controller类型中反射RoutePrefixAttribute,然后得到它的Prefix值。 Controller 实例在 ViewContext 上可用。

    此示例创建了一个方便的 HTML 帮助程序,它将所有步骤包装到一个调用中。

    using System;
    using System.Web.Mvc;
    
    public static class RouteHtmlHelpers
    {
        public static string GetRoutePrefix(this HtmlHelper helper)
        {
            // Get the controller type
            var controllerType = helper.ViewContext.Controller.GetType();
    
            // Get the RoutePrefix Attribute
            var routePrefixAttribute = (RoutePrefixAttribute)Attribute.GetCustomAttribute(
                controllerType, typeof(RoutePrefixAttribute));
    
            // Return the prefix that is defined
            return routePrefixAttribute.Prefix;
        }
    }
    

    那么在你看来,只需要调用扩展方法就可以得到RoutePrefixAttribute的值。

    @Html.GetRoutePrefix() // Returns "Admin/People"
    

    【讨论】:

    • 酷!我认为这很好。我只调整了扩展方法的返回值,以解决没有定义前缀的情况(比如在我的公共控制器中)。 return routePrefixAttribute != null ? routePrefixAttribute.Prefix : null;
    • 在 AttributeRouting 3.5.6.0 中,属性是 Url 而不是 Prefix
    • 这行得通。因为我正在制作 API,所以我不需要视图中的前缀,因此我调整了扩展方法以采用 ApiController 代替,以便可以在后台使用它。谢谢!
    • 单行:helper.ViewContext.Controller.GetType().GetCustomAttribute<RoutePrefixAttribute>.Prefix
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多