Parkash
Parkash

Reputation: 105

MVC multiple Default Routes without controller name

I have got two controllers, one is called Dashboard and the other is called DashboardCash. Now my application can be accessed by two types of users, one who can only access Dashboard (Type A users) while others can only access DashboardCash (Type B users). In order to ensure that I have put a login page.

What I want to do is when Type A users login successfully, I want to show them url with no controller name like http://example.com rather than showing with the controller name such as http://www.example.com/Dashboard. And with Type B users I want to show them the same http://www.example.com but here I am replacing DashboardCash.

Currently I have this mapping code defined in Global.asax file:

routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional
     }, // Parameter defaults
     new string[] { "Merit.Traveller.BMS.Controllers" });

This code works fine for Dashboard now I want to do the same thing for DashboardCash.

Upvotes: 0

Views: 1527

Answers (2)

Parkash
Parkash

Reputation: 105

Thanks Yishai,

That fixed the issue, I just added one more thing which is EliminateController as the constraint, which allows the default route to run only if we dont have the dashboard pages.

Here is the detailed code:

http://jsfiddle.net/hf7wexkk/ For Code

Thanks.

Upvotes: 0

Yishai Galatzer
Yishai Galatzer

Reputation: 8862

Write a custom route constraint that makes the route match based on the user type.

Implement the following interface

public interface IRouteConstraint
{
     bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection);
}

Then use it in the route, something like this:

routes.MapRoute(name: "newRoute1",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Dashboard", action = "Index" },
  constraints: new { name = new UserTypeARouteConstraint() }
);

EDIT - based on your question below here are more details

This is what your second route looks like

routes.MapRoute(name: "newRoute2",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "DashboardCash", action = "Index" },
  constraints: new { name = new UserTypeBRouteConstraint() }
);

And this is what a constraint looks like

public class UserTypeARouteConstraint : IRouteConstraint
{
     bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
     {
         return IsUserOfTypeA(httpContext);
     }

     private bool IsUserOfTypeA(HttpContextbase httpContext)
     {
         // custom logic to figure out the user group
     }
}

Upvotes: 2

Related Questions