首页 > 解决方案 > 如何在 MVC 中设置通配符路由

问题描述

我们网站上任何产品详细信息页面的 URL 如下所示:
http ://example.com/Product/Index/pid219

在哪里:

我希望可以通过
http://example.com/Product/pid219

http://example.com/Product/name-of-the-product/pid219访问此页面

所以,我修改了RouteConfig.cs这个:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

该页面现在可以根据需要访问,但是,在所有其他页面中都存在一个问题,这使得 Ajax 在按钮单击时调用。例如:登录按钮单击不起作用。

控制器名称是 SignIn,有两种方法 - Index(加载页面)、SignInUser(在 ajax 请求上触发)

当我单击登录按钮时,现在点击 Index 方法而不是 SignInUser 方法。

function SignInUser() {    
    $.ajax({
        type: "POST",
        url: '@Url.Action("SignInUser", "SignIn")',            
        data: '',
        contentType: "application/json; charset=utf-8",
        dataType: "json",            
        success: function (response) {                               
        }
    });        
} 

如果我们设置一个新的路由,ajax调用中的url是否也需要更改。请帮助我,我如何在这里实现我的目标。还要指定是否必须在默认路由之前或之后声明新路由。

标签: c#asp.net-mvc

解决方案


我希望这个页面可以作为 http://example.com/Product/pid219http://example.com/Product/name-of-the-product/pid219访问 给你:

routes.MapRoute(
        name: "ProductRoute1",
        url: "Product/{id}",
        defaults: new {controller = "Product", action = "Index", id = "" }
    );

http://example.com/Product/name-of-the-product/pid219

routes.MapRoute(
        name: "ProductRoute1",
        url: "Product/{*action}/{id}",
        defaults: new { controller = "Product", action = "Index", id = "" }
    );

推荐阅读