开发者

How to MapRoute? If http://abc.com/Home go to Home Controller else go to Misc Controller

开发者 https://www.devze.com 2023-01-20 07:26 出处:网络
I have three controllers, Home, Blog and Misc. When I type mydomain.com/Home at the address bar, the browser displays the view for the home controller.

I have three controllers, Home, Blog and Misc.

When I type mydomain.com/Home at the address bar, the browser displays the view for the home controller.

When I type mydomain.com/Blog at the address bar, the browser displays the view for bl开发者_JAVA技巧og controller.

And when I type mydomain.com/anything (not Home nor Blog) the browser displays the view for the misc controller.

How to map route for above?

I mean that when type something other than /Home or /Blog

for example /Test, /Book, /Book/Index, /xxx/yyy/zzz/aaa, /etc/etc/etc,

then my Misc Controller will be launched

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


routes.MapRoute(
     "Misc",
     "{*id}",
      new { controller = "Misc", action = "Index", id = "" },
;


In order to trap the 'other' entries, you need to override the controller factory that determines which controller to use:

protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
    try
    {
        return base.GetControllerInstance(requestContext, controllerType);
    }

    catch (HttpException ex)
    {
        int httpCode = ex.GetHttpCode();
        if(httpCode == (int)HttpStatusCode.NotFound)
        {
            IController controller = new MiscController();
            ((MiscController)controller).DefaultAction(); // whatever action you want to invoke
            return controller;
        }
        else
        {
            throw ex;
        }
    }
}

Then register this controller factory in the Global.asax startup.

0

精彩评论

暂无评论...
验证码 换一张
取 消