Defining conditional routes

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 as admin he uses lets say admin controller, if user is just a user he uses user controller. This is just an example, basically I want to have a function that decides what controller route takes.

Thank u everyone. Any help is greatly appreciated.

PS
Use of this:
Admin has different UI and options,
Output catching,
Separation of concern

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x