【发布时间】:2016-01-22 16:51:49
【问题描述】:
我想设置一个自定义路由约束,允许我用属性装饰控制器,这样我就不必将字符串传递给路由并记住用新的控制器名称更新它。
我以为我可以设置使用IRouteConstraint,但我似乎无法获得该属性。也许我只是在这里遗漏了一些明显的东西。
routes.MapRoute("test",
"foo/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = new TestConstraint()}
);
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
public class TestConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
return false;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class CustomConstraintControllerAttribute : Attribute
{
}
[CustomConstraintController]
public class TestController : Controller
{
public ActionResult Index()
{
return View();
}
}
编辑:
当前方法:
routes.MapSubdomainRoute("Store",
"{store}/{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional},
new {controller = "StoreHome|Contacts|..." }
);
此路由配置确保 url 必须匹配 subdomain.test.com/GiggleInc/Contacts 或 subdomain.test.com/GiggleInc/StoreHome。
subdomain.test.com/GiggleInc/StoreHome
MapSubdomainRoute /{store} /{controller}/{action}/{id}
此方法要求以这种方式使用的每个控制器必须添加到控制器约束中。
正如我在 cmets 中提到的,我想替换属性或类似内容的硬编码字符串。
【问题讨论】:
-
路由已完全完成在控制器被选中。您希望通过约束实现什么?
-
请注意,您可以使用 Attribute Routes 在 MVC 5 中完全设置路由(包括约束),只需将您的路由配置与您的控制器一起放置。
-
这就是我所害怕的。根据我的研究,这就是我认为的答案。我们在项目中使用子域,某些控制器需要存在子域。目前,我们用控制器类名作为字符串填充约束。我希望改为装饰班级
-
虽然如果我在
return false上放置一个断点,它会在请求开始时被命中。我想我可以在AuthorizeAttribute中使用ControllerDescriptor之类的东西 -
请更新您的问题,详细说明您要达到的目标。目前还不清楚
AuthorizeAttribute尚未涵盖的情况。如果用户尝试访问他们“不允许”访问的控制器,您究竟希望应用程序做什么?
标签: asp.net-mvc