How to determine route prefix programmatically in asp.net mvc?

I would like to provide some URL separation for my public / anonymous controllers and views from controllers and admin / authenticated views. Therefore, I made full use of Attribute Routing to have more control over my URLs. I wanted my public urls to start with "~ / admin / etc." while my public urls would not have such a prefix.

Open controller (one of several)

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

Admin Controller (one of several)

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

This allows me to have public URLs like:

http://myapp/home/someaction

... and admin / authenticated URL, for example:

http://myapp/admin/people/someaction

, , "" "" . , ?

, -

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

... "". ,

HttpContext.Current.Request.RequestContext.RouteData.Values

... "admin" , , .

, , , "admin" ?

+4
1

RoutePrefixAttribute Controller, 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"
+7

All Articles