防止访问路由中不需要的默认 URL

Prevent access to unwanted default URLs in Routing

我的项目由所有具有默认索引操作的区域组成。
不过,我只想通过以下 URL 模式访问此操作:

/{area}/

它的控制器是DefaultController,动作名称是Index
现在我似乎可以通过以下 URLs:

访问此索引操作

/import/Default/import/Default/Index。在此示例中,只有 /import/import/ 应该是有效的 URL。

有什么办法可以避免这种情况吗?

ImportAreaRegistration.cs

public override void RegisterArea(AreaRegistrationContext context) 
{
   context.MapRoute(
         name: "Import_default",
         url: "import/{controller}/{action}",
         defaults: new { controller = "Default", action = "Index" },
         namespaces: new string[] { "Tax.Areas.Import.Controllers" }
   );
}

DefaultController.cs

namespace Tax.Areas.Import.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    [RouteArea("import")]
    public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            ...
        }
    }
}

您可以使用 RouteCollection 上的 IgnoreRoute 扩展方法来阻止不需要的路由。请务必在注册您的区域路线之前完成此步骤,以便它们以正确的顺序执行。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Ignore unwanted routes first
        routes.IgnoreRoute("{area}/Default");
        routes.IgnoreRoute("{area}/Default/Index");

        // Then register your areas (move this line here from Global.asax)
        AreaRegistration.RegisterAllAreas();

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

或者,您可以通过执行以下操作忽略 RegisterArea 方法中的路由:

public override void RegisterArea(AreaRegistrationContext context) 
{
    context.Routes.Add(new Route("import/Default", new StopRoutingHandler()));
    context.Routes.Add(new Route("import/Default/Index", new StopRoutingHandler()));

    context.MapRoute(
        name: "Import_default",
        url: "import/{controller}/{action}",
        defaults: new { controller = "Default", action = "Index" },
        namespaces: new string[] { "Tax.Areas.Import.Controllers" }
    );
}