c# - 如何在 MVC 中设置通配符路由
问题描述
我们网站上任何产品详细信息页面的 URL 如下所示:
http ://example.com/Product/Index/pid219
在哪里:
- Product - 是控制器的名称
- 索引 - 是方法的名称和
- pid219 - 产品 ID
我希望可以通过
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是否也需要更改。请帮助我,我如何在这里实现我的目标。还要指定是否必须在默认路由之前或之后声明新路由。
解决方案
我希望这个页面可以作为 http://example.com/Product/pid219 或 http://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 = "" }
);
推荐阅读
- javascript - 找不到模块“提示同步”
- python - PULSE on github(提供链接) RuntimeError: CUDA out of memory....阻止程序“run.py”执行
- javascript - 控制台日志 ({value}) 与 console.log(value) 不同
- java - sun.net.www.protocol.file 将代码从 1.6 jdk 迁移到 11 jdk 问题
- c# - 使用 Navigation.PushAsync 加载新页面时退出提示不起作用
- swift - 将字符串时间快速转换为日期
- json - Spark将文件读入数据框
- jenkins - 将 SonarQube 与詹金斯集成
- c - 将结构传递给 Cosmic 编译器和 STM8 中的函数时出现“无效的间接操作数”错误
- php - php数组相关查询