c# - MVC 常规和属性路由不能一起工作
问题描述
我在 ASP.Net MVC 项目上使用传统路由,并希望并行启用属性路由。我创建了以下内容,但是在启用属性路由时,我在常规路由上得到了 404
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
控制器
[RoutePrefix("Registration")]
public class RegistrationController : Controller
{
[HttpGet]
[Route("Add/{eventId}")]
public ActionResult Add(int eventId)
{
}
}
打电话
http://localhost/Registration/Add/1
工作,同时调用
http://localhost/Registration/Add?eventId=1
不再工作并以404 NotFound响应
解决方案
如果您{eventId}
在路由模板中将模板参数设为可选,则应该可以使用
[RoutePrefix("Registration")]
public class RegistrationController : Controller {
//GET Registration/Add/1
//GET Registration/Add?eventId=1
[HttpGet]
[Route("Add/{eventId:int?}")]
public ActionResult Add(int eventId) {
//...
}
}
两者不起作用的原因是路由模板Add/{eventId}
意味着路由只有在{eventId}
存在时才会匹配,这就是为什么
http://localhost/Registration/Add/1
作品。
通过使其 ( eventId
) 可选eventid?
,它将允许
http://localhost/Registration/Add
不需要作为模板参数工作。现在这将允许使用查询字符串?eventId=1
,路由表将使用该查询字符串来匹配int eventId
操作上的参数参数。
http://localhost/Registration/Add?eventId=1
推荐阅读
- c# - 使用 FireFox 而非 Chrome 时发生双重回发
- python - Django - 注册重定向到登录页面不起作用
- javascript - 从 Microsoft Graph API(测试版)通信 API 获取实时更新
- android - 如何将图像放在文本中间的文本下方?
- environment-variables - 如何在 Atom 中运行 python 文件?康达环境?
- javascript - 无法设置未定义的属性“selectedIndex”
- python - 我想通过python从文本文件中提取特定数据
- laravel - How to set custom header in elibyy/tcpdf-laravel
- javascript - JavaScript 和 JQuery 代码如何从 MVC 视图移动到 Visual Studio 2017 的外部 .js 文件?
- javascript - jQuery(文档).ready(函数(){}); 不能正常工作