【问题标题】:ASP.NET MVC: Determine area+controller+action of urlASP.NET MVC:确定区域+控制器+url的动作
【发布时间】:2014-02-19 11:34:57
【问题描述】:

情况:我正在使用 MVC 的 AuthorizeAttribute 保护我的操作。我有几个 UI 组件,其中包含 INSERT、DELETE 等功能,如果应用程序的最终用户点击例如一个按钮。只有那些允许他执行的按钮对用户是可见的。为了避免至少两次为用户操作(按钮和控制器操作)放置权限,我正在考虑按钮可以确定控制器的 AuthorizeAttribute 和/或操作以控制其可见性。常规:应用程序有多个区域和控制器。

我找到了这个答案 (Accessing the list of Controllers/Actions in an ASP.NET MVC application),它表明 ReflectedControllerDescriptor 类可以提供帮助。

有没有办法根据 url 确定 mvc 应用程序中现有路由的区域、控制器和操作?

一个例子:

我有一个视图:/shop/products/all

此视图包含两个链接 - /商店/用户/推荐 - /system/users/loggedon

“recommend”和“loggedon”操作被 Authorize-attribute 修饰,这些链接只有在用户被允许执行时才可见。因此,如果可能的话,我想使用已经附加的属性。

【问题讨论】:

  • 你想在视图中获取控制器、动作等名称吗?
  • 是的 - View, PartialView, ... 但它可能是与视图控制器不同的控制器,因为不同的控制器可能负责存储数据。
  • 检查我的答案,如果有帮助,请告诉我。
  • 我删除了我的答案,因为它对您的要求没有任何意义。

标签: c# asp.net-mvc asp.net-mvc-4 routes


【解决方案1】:

我就是这样做的。

我已经更新了答案。它适用于 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)
    }

我希望这能让你开始。这样,您的逻辑将保留在一个位置,并可用于编辑/删除类型链接以及控制器。

【讨论】:

  • 到目前为止合理的逻辑 - 关于那条线并假设有区域:“return UserisAllowed(_conroller, _action, _id);”如何确定区域的控制器,看动作是否被属性修饰?
  • 我想你可以通过 actionContext.RouteData.Values["area"];我还没有测试过。
  • 我想在action没有执行的时候访问它。如果执行了操作,则会调用代码中的“OnActionExecuting”。但就我而言,我指的是未执行的操作。
  • 未执行的操作是什么意思。我只是在回答如何将您的逻辑编写一次并使用它两次。
  • 示例:该属性分配给返回视图 VA 的操作 A。用户使用视图 VB 打开操作 B,现在我想确定是否显示指向 A 和 VA 的链接。我怎样才能得到A的属性?我知道 A 的区域和 B 中的 A 控制器作为字符串... A 没有执行但我想得到定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
相关资源
最近更新 更多