[英]ASP.NET MVC: Determine area+controller+action of url
情况:我正在使用MVC的AuthorizeAttribute保护我的动作。 我有几个包含INSERT,DELETE等功能的UI组件,如果应用程序的最终用户单击某个按钮,这些组件将导致操作。 只有那些允许用户执行的按钮才对用户可见。 为了避免至少两次获得用户操作许可(按钮和控制器操作),我在考虑该按钮可以确定控制器和/或操作的AuthorizeAttribute来控制其可见性。 常规:应用程序具有多个区域和控制器。
我找到了这个答案( 访问ASP.NET MVC应用程序中的Controllers / Actions列表 ),它表明ReflectedControllerDescriptor类可以提供帮助。
有没有一种方法可以从url中确定与mvc-application中现有路由有关的区域,控制器和操作?
一个例子:
我有一个观点:/ shop / products / all
该视图包含两个链接-/ shop / user / recommend-/ system / users / loggedon
动作“ recommend”和“ loggedon”用Authorize属性修饰,并且只有在允许用户执行这些链接的情况下,这些链接才可见。 因此,如果可能的话,我想使用已经附加的属性。
这就是我做的。
我已经更新了答案。 它适用于mvc3。
public class MyActionAttribute : ActionFilterAttribute
{
private readonly string _conroller;
private readonly string _action;
private readonly string _id;
public class MyActionAttribute : ActionFilterAttribute
{
public bool IsAllowed(string _conroller, string _action, string _id)
{
//write your logic to check if a user is allowed to perform the given action on this controller,action and id
return UserisAllowed(_conroller, _action, _id);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var area =filterContext.RouteData.DataTokens["area"];
if (!IsAllowed(filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName, filterContext.RouteData.DataTokens["id"].ToString()))
{
//send user to somewhere saying you are not allow
return;
}
base.OnActionExecuting(filterContext);
}
}
现在将此属性应用于控制器操作。
[MyAction]
public ActionResult Someview()
{
return View();
}
对于链接,您可以通过这种方式检查
if (new MyActionAttribute().IsAllowed("yourcontroller","youraction","id"))
{
Html.ActionLink(whatever)
}
我希望这可以让您开始。 这样,您的逻辑就保留在一个地方,可以用于编辑/删除类型链接,也可以用于控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.