ASP.NET MVC:确定url的区域+控制器+动作

时间:2014-02-19 11:34:58

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

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

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

有没有办法从网址确定mvc-application中现有路由的区域和控制器以及操作?

一个例子:

我有一个观点:/ shop / products / all

此视图包含两个链接 - / shop / user / recommended - / system / users / loggedon

使用Authorize属性对“推荐”和“登录”操作进行处理,只有在允许用户执行这些链接时,这些链接才可见。因此,如果可能,我想使用已经附加的属性。

1 个答案:

答案 0 :(得分: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)
    }

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