我在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响应
2 回答
如果在路径模板中使
{eventId}
template参数可选,则应该有效这两个不工作的原因是路由模板
Add/{eventId}
意味着路由只有在{eventId}
存在时才匹配,这就是为什么作品 .
通过使它(
eventId
)可选eventid?
它将允许作为模板参数工作不是必需的 . 现在,这将允许使用查询字符串
?eventId=1
,路由表将使用该字符串来匹配操作上的int eventId
参数参数 .我也遇到了这个问题 . 您使用的是哪个MVC版本?我在asp.net核心中遇到了MVC这个问题 . 我认为这是一个缺陷,就像你在任何动作方法上提供路由属性一样,它的传统路线被过度使用并且不再可用,因此你得到404错误 . 为此,您可以为此操作方法提供另一个Route属性 . 这会奏效