【问题标题】:MVC Conventional and Attribute routing not working togetherMVC 常规和属性路由不能一起工作
【发布时间】:2018-10-09 10:12:51
【问题描述】:

我在 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

响应

【问题讨论】:

  • 你的控制器叫做RegistrationController,所以,使用基于约定的路由,它的路由是:http://localhost/Registration/Add而不是http:/localhost/Register/Add
  • 对不起,这是一个错字和误导,我已经更新了代码。控制器应该用 [RoutePrefix()] 标记,而在我之前将其标记为 [Route()]
  • 所以听起来我只能使用其中一个?想法是保留常规路由以保留书签等,但逐渐将用户切换到基于属性的链接
  • 似乎任何“直接路由”(具有至少一个Route 属性的操作)都会从传统路由中删除该操作。一种解决方法可能是定义不同的 Route 属性,以保持旧的行为。

标签: c# asp.net-mvc asp.net-mvc-routing attributerouting


【解决方案1】:

如果您在路由模板中将{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

【讨论】:

  • 这种对我有用。如果我有一个带有两个参数的操作,例如 public ActionResult Information(int? personId, string level = ""){} 那么调用 localhost:54659/Registration/Information?personId=5592 不起作用。我的 RouteConfig.cs 有问题吗?
  • @Adrian 是否也使用了属性路由?
  • 基本上每个与传统路由一起使用的控制器操作,我想扩展它以并行使用属性路由。因此,当我将人们迁移到属性路由时,我需要“旧样式”来工作
【解决方案2】:

我也遇到了这个问题。您使用的是哪个 MVC 版本? 我在 asp.net 核心中遇到了 MVC 的这个问题。 我认为这是一个缺陷,就好像您在任何操作方法上提供 Routing 属性一样,它的常规路由已被覆盖并且不再可用,因此您会收到 404 错误。 为此,您可以像这样为您的操作方法提供另一个 Route 属性。这将起作用

 [Route("Add/{eventId}")]  
 [Route("Add")]

【讨论】:

    猜你喜欢
    • 2017-01-16
    • 2013-06-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多