Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 909
Goran Žuri Avatar asked May 04 '11 18:05

Goran Žuri


1 Answers

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

like image 135
counsellorben Avatar answered Oct 23 '22 22:10

counsellorben