asp.net-mvc - 属性路由在区域中不起作用

标签 asp.net-mvc asp.net-mvc-routing

场景:我的 ASP.NET MVC 5 站点中有一个表单区域。

我正在尝试重定向到详细信息操作,该操作使用使用新的属性路由功能定义的自定义路由。

重定向到操作:

return RedirectToAction("Details", new { slug });

我重定向到的操作:

[HttpGet]
[Route("forms/{slug}")]
public ActionResult Details(string slug)
{
    var form = FormRepository.Get(slug);

    ...

    return View(model);
}

我希望重定向到http://localhost/forms/my-slug,但应用程序将我重定向到http://localhost/Forms/Details?slug=我的-slug

这意味着属性路由不起作用。

如何解决这个问题?

我添加了routes.MapMvcAttributeRoutes();行到我的 RouteConfig:

public class RouteConfig
{
    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 }
        );
    }
}

这是我的 Application_Start():

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

最佳答案

您可能将基于约定的路由与属性路由结合起来,并且您应该在映射属性路由后注册您的区域

线路

AreaRegistration.RegisterAllAreas();

应在此行之后调用:

routes.MapMvcAttributeRoutes();

解释(来自https://devblogs.microsoft.com/aspnet/attribute-routing-in-asp-net-mvc-5/):

If you are using both Areas with route attributes, and areas with convention based routes (set by an AreaRegistration class), then you need to make sure that area registration happen after MVC attribute routes are configured, however before the default convention-based route is set. The reason is that route registration should be ordered from the most specific (attributes) through more general (area registration) to the mist generic (the default route) to avoid generic routes from “hiding” more specific routes by matching incoming requests too early in the pipeline.

当你创建一个空白的asp.net mvc网站,添加一个区域并开始使用属性路由时,你会遇到这个问题,因为Visual Studio中的“添加区域”操作在你的Application_Start中添加了RegisterAllAreas调用,在路由配置之前..

替代解决方案

也许您不打算继续使用基于约定的路由,而更愿意仅使用属性路由。 在这种情况下,您只需删除 FormsAreaRegistration.cs 文件即可。

关于asp.net-mvc - 属性路由在区域中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20466960/

相关文章:

asp.net-mvc - 缺少RouteData DataToken

c# - 404 时重定向到 home/index

c# - 如何动态更改 MVC 注册的 Bundle 集合项

javascript - 提前输入自动完成抛出错误

asp.net-mvc-routing - ASP.NET MVC 区域 : How to hide "Area" name in URL?

ASP.NET MVC 自定义路由 很长的自定义路由在我脑海中没有出现

asp.net-mvc - 使用 MvcContrib.TestHelper 的 ShouldMapTo() 通用扩展方法需要帮助解决错误

c# - 将 View 呈现为字符串 : ArgumentOutOfRangeException

asp.net-web-api - 网址链接() : Route cannot be found when using attribute routing

c# - 是否可以在 Controller 外部的运行时获取路由数据?