Wildcards with ASP.NET MVC MapPageRoute to support organizing legacy code

元气小坏坏 提交于 2019-12-01 21:21:28

问题


I'm working on migrating an existing ASP.NET web site into an MVC project. There are several (60+) pages that I don't want to rewrite just yet, and so I'm wondering if there's a way that I can:

  • Move the existing .aspx pages (both markup and code-behind files) into a 'Legacy' folder in my MVC structure
  • Set up routing so a call to /foo.aspx (without 'legacy') will actually invoke ~/Legacy/foo.aspx

Effectively, I don't want "legacy" in the URL, but I also don't want the MVC solution to be full of legacy .aspx pages. I accept that this is a very minor point, I'm just curious if it can be done with Routing.

I realize I could do:

routes.MapPageRoute("legacy-foo", "Foo.aspx", "~/Legacy/Foo.aspx"); 

but I'm wondering if there is a way to do that dynamically (using MVC routes)? eg:

routes.MapPageRoute("legacyroutes", "{filename}.aspx", "~/Legacy/{filename}.aspx"); 

I guess one way is to use a URL rewriter module, but that seems a bit redundant if routes is capable of doing this natively.


回答1:


I solved this using a controller which returns the contents of the file. It is not a perfect and fast solution but it works.

routes.MapRoute(
    "legacyroutes",
    "{filename}.aspx",
    new { controller = "Home", action = "RedirectFile"}
); 

And the controller:

public class HomeController : Controller
{
    public ActionResult RedirectFile(string filename)
    {
        string url = Url.Content("~/Legacy/"+filename+".aspx");
        Redirect(url); // or other code to process the file
    }
}

Details and other examples here: http://maxivak.com/dynamic-url-rewriting-on-asp-net-mvc/




回答2:


Not sure if you still need this, but you could solve this with a dirty solution:

Use HttpContext.Current.Request.MapPath("") to get the physical location of the route, and then loop over all aspx files (and anything else you want to map) using the DirectoryInfo/FileInfo classes. You can then dynamically register alternative paths for your files.

I've done a prototype and it appears to be working, although of course, the devil is always in the details.

Cheers,



来源:https://stackoverflow.com/questions/3348360/wildcards-with-asp-net-mvc-mappageroute-to-support-organizing-legacy-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!