0
votes

This is how i designed the RegisterRoutes function. and based on the condition am selecting the Action for HomeController. So far so Good.

string env = "Index";
if (some condition from config)
{
    env = "Test";
}
routes.MapRoute(
    "Default",                                             
    "{controller}/{action}/{id}",                           
    new { controller = "Home", action = env, id = "" }  
);

Problem starts here when am reirecting to other controller by default if dont specify an action(for eg: am calling SampleController) the "env"(Which was set in RegisterRoutes is called. if env is set as "Index" Index action is called, if env is set "Test" Test action is called in all other controllers as well.

My intention is only for HomeController this condition should be set and for all other controller i want Index to be the default action.

How do i make this work ? is it possible to dynamically change the action for all other controllers ? Is there a better way i can do this.

Share your suggestions

Thanks

1
You could make one specific route for "Home/{action}/{id}", new { controller = "Home", action = env } and the default route "{controller}/{action}/{id}", new { controller = "Home", action = "Index" } - user3559349
@StephenMuecke Thanks! I tried but always the default route is getting called ? - Peru
Did you put "Home/{action}/{id}" first? (the order is important) - user3559349

1 Answers

2
votes

I don't think you should do this in your routing engine. I would route everything in code and call the correct action from in there. For example:

public ActionResult Index()
{
    switch(config) 
    {
        case "OtherAction":
            return OtherAction();

        case "AnotherAction":
            return AnotherAction();

        case "Index":
            break;

        default:
            //Er, how did we get here?
            throw new HttpNotFoundException();
    }

    //Normal index action continues here...

}

public ActionResult OtherAction() { ... }
public ActionResult AnotherAction() { ... }