将请求重定向到匹配的控制器

时间:2011-07-10 04:00:55

标签: asp.net-mvc asp.net-mvc-3

如果用户点击http://somewebsite/Cnt但我没有该名称的控制器,我想将用户重定向到http://somewebsite/Country。同样,如果用户点击/ofr,我会将其重定向到/Offer

我该怎么做?

2 个答案:

答案 0 :(得分:1)

首先,您可以创建将处理缩短路由的RouteHandler - 不重复MvcHandler的整个代码,您可以从中派生并替换RouteData [“controller”],并让{{ 1}}执行

MvcHandler

而不仅仅是注册这个处理程序而不是MvcHandler(这是默认情况下为所有mvc路由注册的)

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);
    }
}

如果您不希望所有请求都通过额外检查它们是否缩短,您可以创建另一个路由并为其{controller}值设置约束

答案 1 :(得分:0)

听起来您想要确定用户何时点击您网站上不存在的网址并将其发送到现有网页。如果这是你想要的,那么在Global.asax.cs文件中更新你的最后一条路线,指向你的“国家”页面:

routes.MapRoute(null, "{*url}", 
       new { controller = "Country", 
       action = "Index" }
);
相关问题