How to redirect all actions to one action

淺唱寂寞╮ 提交于 2019-12-23 02:17:49

问题


i want to re-direct all actions under a controller to its index action (one that controller, other controllers will remain default behavior)

e.g for controller "O"

   http://foo.com/o/abc
   http://foo.com/o
   http://foo.com/o/abc?foo=bar

all the above request will all go to "index" action

I tried to use below route setting, but ASP.NET complain 404 when i try to visit "http://foo.com/o/abc".

routes.MapRoute(
                name: "ORoute",
                url: "o/*",
                defaults: new { controller = "O", action = "Index" });

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

Thanks


回答1:


Try this-

routes.MapRoute(
    "O",
    "O/{action}",
    new { controller = "O", action = "Index" }
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
);

The order of routes changes everything. Also, notice the changes I made to the O route. The first parameter is the name of the route. Second is the URL, which match URLs that start with O, and allows for other actions in your O controller. As you can see, it will default to the Index action.




回答2:


First , define a controller named Error with One Action which show Customized Invalid Address page ..

Then you need to define a Class with inherit DefaultControllerFactory ( it's name is CF)

and Then you should override its Main Method : CreateController

and finally , add this statement to global.asax which means any request should be verified by this Class.

CF Class Code:

public class CF : DefaultControllerFactory
{
    public override IController CreateController(RequestContext requestContext, string controllerName)
    {
        IController result;
        try
        {
            result = base.CreateController(requestContext, controllerName);
        }
        catch (Exception)
        {
            result = base.CreateController(requestContext, "Error");

        }
        return result;

    }
}

Global.asax :

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            // Here is the Change
            ControllerBuilder.Current.SetControllerFactory(typeof(CF));
        }


来源:https://stackoverflow.com/questions/25860980/how-to-redirect-all-actions-to-one-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!