我的项目包含所有都有默认索引操作的区域 但是,我希望只使用以下URL模式访问此操作:
/{area}/
其控制器为DefaultController
,操作名称为Index
现在,我似乎能够使用以下两个URL访问此索引操作:
/import/Default
和/import/Default/Index
。在此示例中,只有/import
或/import/
应该是有效的网址。
有什么方法可以阻止这种情况吗?
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()
{
...
}
}
}
答案 0 :(得分:1)
您可以使用IgnoreRoute
上的RouteCollection
扩展名方法阻止不需要的路由。重要的是,在注册区域路线之前完成此步骤,以便按正确的顺序执行。
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" }
);
}