How to redirect all actions to one action

混江龙づ霸主 提交于 2019-12-06 22:53:33

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.

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