我需要在我的asp.net mvc項目中支持以下url一段時間。在asp.net mvc項目中路由遺留的asp.net鏈接
http://www.example.com/d.aspx?did=1234
我需要將此映射到此URL。
http://www.example.com/Dispute/Detail/1234
我已經看過以下信息。
http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx
ASP.Net MVC routing legacy URLs passing querystring Ids to controller actions
在努力遵循這個我能得到第一個URL工作,但那麼所有其他的URL被破壞。 任何人都可以看到我的出錯位置嗎?
這是我的路線。
public static void RegisterRoutes(RouteCollection routes)
{
// all my other routes
// Legacy routes
routes.Add(
"Legacy",
new LegacyRoute(
"d.aspx",
"LegacyDirectDispute",
new LegacyRouteHandler())
);
routes.MapRoute(
"LegacyDirectDispute",
"Dispute/Details/{id}",
new { controller = "Dispute", action = "Details", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
這是我使用的global.asax.cs中的代碼。
public class LegacyRoute : Route
{
public string RedirectActionName { get; set; }
public LegacyRoute(string url, string redirectActionName, IRouteHandler routeHandler)
: base(url, routeHandler)
{
RedirectActionName = redirectActionName;
}
}
// The legacy route handler, used for getting the HttpHandler for the request
public class LegacyRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new LegacyHandler(requestContext);
}
}
// The legacy HttpHandler that handles the request
public class LegacyHandler : MvcHandler
{
private RequestContext requestContext;
public LegacyHandler(RequestContext requestContext)
: base(requestContext)
{
this.requestContext = requestContext;
}
protected override void ProcessRequest(HttpContextBase httpContext)
{
string redirectActionName = ((LegacyRoute)RequestContext.RouteData.Route).RedirectActionName;
var queryString = requestContext.HttpContext.Request.QueryString;
foreach (var key in queryString.AllKeys)
{
if (key.Equals("did"))
{
requestContext.RouteData.Values.Add("id", queryString["did"]);
}
else
{
requestContext.RouteData.Values.Add(key, queryString[key]);
}
}
VirtualPathData path = RouteTable.Routes.GetVirtualPath(requestContext, redirectActionName,
requestContext.RouteData.Values);
if (path != null)
{
httpContext.Response.Status = "301 Moved Permanently";
httpContext.Response.AppendHeader("Location", path.VirtualPath);
}
}
}
在這裏得到解答:http://stackoverflow.com/questions/817325/asp-net-mvc-routing-legacy-urls-passing-querystring-ids-to-controller-actions/818370#818370 – 2010-01-18 21:08:31
@ marwan-auida請閱讀問題內容。我已經看過並閱讀過這個問題,我甚至在我的問題中有一個鏈接。 – MHinton 2010-01-18 21:13:45
我的網址被破壞的意思是在添加LegacyRouteHandler代碼之前,我有像http://www.example.com/News這樣的鏈接,現在他們出現了http://www.example.com/d.aspx?行動=指數及控制器=新聞。 – MHinton 2010-01-18 21:27:41