Defining conditional routes

后端 未结 1 1798
谎友^
谎友^ 2021-01-04 23:56

I\'ve been searching for something similar but no luck. I want to build an app that uses different controllers for same urls. Basic idea is like that if a user is logged in

相关标签:
1条回答
  • 2021-01-05 00:11

    You need to create a RouteConstraint to check the user's role, as follows:

    using System;
    using System.Web; 
    using System.Web.Routing;
    
    namespace Examples.Extensions
    {
        public class MustBeAdmin : IRouteConstraint
        {
            public MustBeAdmin()
            { }
    
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
            {
                // return true if user is in Admin role
                return httpContext.User.IsInRole("Admin");
            }
        }
    }
    

    Then, before your default route, declare a route for the Admin role, as follows:

    routes.MapRoute(
        "Admins", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Admin", action = "Index", id = UrlParameter.Optional }, // Parameter default
        new { controller = new MustBeAdmin() }  // our constraint
    );
    

    counsellorben

    0 讨论(0)
提交回复
热议问题