asp.net-mvc – 属性路由不工作在区域

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 属性路由不工作在区域前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
场景:我有一个窗体区域在我的ASP.NET MVC 5网站。

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

RedirectToAction:

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 = my-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();

应该调用AFTER这行:

routes.MapMvcAttributeRoutes();

解释(从http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#route-areas):

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中的“添加区域”操作添加RegisterAllAreas调用在您的Application_Start,在路由配置之前。

替代解决方

也许你不打算继续使用基于约定的路由,并且更喜欢只使用属性路由。在这种情况下,您可以只删除FormsAreaRegistration.cs文件

原文链接:https://www.f2er.com/aspnet/254700.html

猜你在找的asp.Net相关文章