我创建了一个自定义路由处理程序,它在路由级别进行重定向。感谢菲尔哈克。
这是完整的工作。
重定向路由处理程序
public class RedirectRouteHandler : IRouteHandler
{
private string _redirectUrl;
public RedirectRouteHandler(string redirectUrl)
{
_redirectUrl = redirectUrl;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
if (_redirectUrl.StartsWith("~/"))
{
string virtualPath = _redirectUrl.Substring(2);
Route route = new Route(virtualPath, null);
var vpd = route.GetVirtualPath(requestContext,
requestContext.RouteData.Values);
if (vpd != null)
{
_redirectUrl = "~/" + vpd.VirtualPath;
}
}
return new RedirectHandler(_redirectUrl, false);
}
}
重定向 http 处理程序
public class RedirectHandler : IHttpHandler
{
private readonly string _redirectUrl;
public RedirectHandler(string redirectUrl, bool isReusable)
{
_redirectUrl = redirectUrl;
IsReusable = isReusable;
}
public bool IsReusable { get; private set; }
public void ProcessRequest(HttpContext context)
{
context.Response.Status = "301 Moved Permanently";
context.Response.StatusCode = 301;
context.Response.AddHeader("Location", _redirectUrl);
}
}
路线扩展
public static class RouteExtensions
{
public static void Redirect(this RouteCollection routes, string url, string redirectUrl)
{
routes.Add(new Route(url, new RedirectRouteHandler(redirectUrl)));
}
}
有了所有这些,我可以在 Global.asax.cs 中映射路由时做这样的事情。
routes.Redirect("", "/uk/Home/Index");
routes.Redirect("uk", "/uk/Home/Index");
routes.Redirect("uk/Home", "/uk/Home/Index");
.. other routes