c# - 混合 ASP.NET 和 MVC 路由

标签 c# asp.net asp.net-mvc url routes

我认为我可以为我的混合 ASP.NET + MVC 应用程序中的所有路由提供友好的 URL,但它并没有像我预期的那样工作。这是我的路由定义设置:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapPageRoute("Design-Fancy", "Design/Fancy/{*queryvalues}", "~/Design/example10.aspx", true);
    routes.MapPageRoute("Design-Simple", "Design/Simple/{*queryvalues}", "~/Design/example5.aspx", true);

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    );
}

虽然这可以路由到 *.aspx 页面,但同一页面上的任何 Razor 操作标签(例如定义为 Controller 的“主页”和操作的“关于”)实际上在页面源中呈现为' http://..../Design/Fancy?action=About&controller=Home '.所以,这会破坏所有导航菜单 URL 等。我一定是做错了!

最佳答案

这是我确定的解决方案。我安装了 NuGet Microsoft.AspNet.FriendlyUrls 包。然后,我将 .aspx 页面命名为没有扩展名看起来不错的页面名称。然后我设置路由如下:


    public static void RegisterRoutes(RouteCollection routes)
    {
        FriendlyUrlSettings aspxSettings = new FriendlyUrlSettings();
        aspxSettings.AutoRedirectMode = RedirectMode.Off;  // default=Off
        routes.EnableFriendlyUrls(aspxSettings);

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        );

        routes.MapPageRoute("Design-Fancy", "Design/Fancy/{*queryvalues}", "~/Design/Fancy.aspx", true);
        routes.MapPageRoute("Design-Simple", "Design/Simple/{*queryvalues}", "~/Design/Simple.aspx", true);
    } 

这提供了我想要的效果,并与我的 MVC 路由一起工作,结果在删除 .aspx 扩展名的同时路由到 .aspx 页面。

关于c# - 混合 ASP.NET 和 MVC 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34910608/

相关文章:

c# - 激活器创建通用实例

c# - 将显式强制转换作为 ref 参数传递 (C#)

c# - Insert 语句不会插入 Null 值

c# - Dropzone.js 已附加

c# - 手动在 AppFabric 中缓存 MVC View

具有默认参数值的c#方法不会生成没有参数的重载?

c# - ASP.NET 控件可以在 WinForms 中使用吗?

c# - 与我将它作为 Windows 应用程序运行时相比,WebMethod() 在每次执行时都很慢

asp.net-mvc - 如何在 Azure 上运行的 MVC 3 中将 session 信息从一个屏幕传递到另一个屏幕

c# - 是否可以 StreamWrite DataList 结果来制作 HTML 文件? (ASP.NET)