开发者

Redirect request to matching controller

If user hits http://someweb开发者_开发知识库site/Cnt but i dont have controller with that name and i would like to redirect user to http://somewebsite/Country. Same way if user hits /ofr then i will redirect him to /Offer.

How do i do that?


First, you could create RouteHandler that would handle shortened routes - to not repeat entire code of MvcHandler, you could just derive from it and replace RouteData["controller"], and let MvcHandler execute

public class ShortenedUrlHandler : MvcRouteHandler
{
    public static Dictionary<string, string> _shortenedControllers = new Dictionary<string, string>
    {
        { "Cnt", "Country" },
        { "Ofr", "Offer"}
    };

    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        string shortenedControllerName = requestContext.RouteData.Values["controller"].ToString();

        if (_shortenedControllers.ContainsKey(shortenedControllerName))
        {
            requestContext.RouteData.Values["controller"] = _shortenedControllers[shortenedControllerName];
        }

        return base.GetHttpHandler(requestContext);
    }
}

than just register this handler instead of MvcHandler (this is registered by default for all mvc routes)

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

If you do not want all the requests to pass additional check whether they are shortened or not, you could create another route and set constraints for its {controller} value


Sounds like you want to identify when a user hits a non-existent url on your site and send them to a existing page. If this is what you want then update your last route in your Global.asax.cs file to point to your "Country" page:

routes.MapRoute(null, "{*url}", 
       new { controller = "Country", 
       action = "Index" }
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜