首页 > 解决方案 > 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响应

标签: c#asp.net-mvcasp.net-mvc-routingattributerouting

解决方案


如果您{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

推荐阅读