路线上的限制

时间:2017-06-01 13:48:00

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

所以我有ASP.NET MVC应用程序。我想配置它的路由。这是我的RouteConfig的代码:

public static void Register(RouteCollection routes, bool useAttributes = true)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("favicon.ico");    

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

这条路线运作正常。此外,我的应用程序中有一个区域,并尝试配置其路由。这是我的区域注册码:

public override void RegisterArea(AreaRegistrationContext context)
{
    try
    {                                                           
        context.MapRoute(
            name: "SiteSettings_Controller",
            url: "SiteSettings/{controller}/{action}/{id}",
            defaults: new {action = "Index", id = UrlParameter.Optional,
            // here I tried to use @"(UserManagement|Tools|Settings)" 
            //as constraint but it takes no effect
            constraints: new {controller = "UserManagement|Tools|Settings" }
        );                              
    }
    catch (Exception e)
    {
        // here I get InvalidOperationException ""
    }        
}

我想在SiteSettingsArea的路由中限制控制器,但是当我转到" localhost / SiteSettings / UserManagement" url我收到带有消息&#34的InvalidOperationException;路由表中没有路由匹配提供的值"。我相信这个url对应于SiteSettings_Controller路由,但显然我错了。我怎样才能正确限制路线中的控制器?

1 个答案:

答案 0 :(得分:1)

如果您在代码库中搜索SiteSettings_Controller它是否会出现在其他地方?

以下代码在我刚测试时确实对我有用。

using System;
using System.Web.Mvc;

namespace WebApplication1.Areas.SiteSettings
{
    public class SiteSettingsAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "SiteSettings";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                name: "SiteSettings_Controller",
                url: "SiteSettings/{controller}/{action}/{id}",
                defaults: new
                {
                    action = "Index",
                    id = UrlParameter.Optional
                },
            constraints: new { controller = "UserManagement|Tools|Settings" }
            );
        }
    }
}