如果用户点击 http://somewebsite/Cnt
但我没有该名称的 Controller ,我想将用户重定向到 http://somewebsite/Country
.如果用户点击 /ofr
,则方法相同然后我会将他重定向到 /Offer
.
我怎么做?
最佳答案
首先,您可以创建 RouteHandler
这将处理缩短的路线 - 不重复 MvcHandler
的整个代码,您可以从中派生并替换 RouteData["controller"],然后让 MvcHandler
执行
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);
}
}
不仅仅是注册这个处理程序而不是 MvcHandler (这是默认为所有 mvc 路由注册的)
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Default", action = "Index", id = UrlParameter.Optional } // Parameter defaults
).RouteHandler = new ShortenedUrlHandler();
如果您不希望所有请求都通过额外检查它们是否被缩短,您可以创建另一个路由并为其 {controller} 值设置约束
关于asp.net-mvc - 将请求重定向到匹配的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6639077/