C# 通过检查访问权限隐藏ActionLink的通用方法

C# 通过检查访问权限隐藏ActionLink的通用方法,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我已经编写了一个自定义筛选器属性来检查每个控制器操作,如果用户有权访问该操作,我将授予访问权限,否则我将重定向到控制器未经授权的访问,以下是我的代码: public class AuthorizationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string actionName

我已经编写了一个自定义筛选器属性来检查每个控制器操作,如果用户有权访问该操作,我将授予访问权限,否则我将重定向到控制器未经授权的访问,以下是我的代码:

public class AuthorizationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string actionName = filterContext.ActionDescriptor.ActionName;
        string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

        if (!CheckAccessRight(actionName, controllerName))
        {
            string redirectUrl = string.Format("?returnUrl={0}", filterContext.HttpContext.Request.Url.PathAndQuery);

            filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
        }
        else
        {
            base.OnActionExecuting(filterContext);
        }
    }
}
以下是我的CheckAccessRight方法:

private bool CheckAccessRight(string Action, string Controller)
{
    if (HttpContext.Current.Session["userId"] != null)
    {
        string userID = HttpContext.Current.Session["userId"].ToString();
        using (var db = new cloud_clinicEntities())
        {
            assignment objAss = db.assignments.SingleOrDefault(model => model.userid == userID);

            String UserRole = objAss.itemname;

            itemchildren objChild = db.itemchildrens.SingleOrDefault(model => model.parent == UserRole && model.child == Controller + " " + Action);

            if (objChild != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    else
    {
        return false;
    }
}

现在,我想在我的每个视图上,如果有指向控制器操作的操作链接,而用户无权访问该操作,则不应在页面上呈现该操作或将其隐藏。如何以一般的方式做到这一点,我想我可以通过在每个操作链接上添加if语句来做到,但我不认为这是更好的方法。

创建一个HTML帮助程序,这是对普通操作链接的一种扩展,但它还需要一个参数,即角色字符串,如下所示


但如果我有一些锚定标签,比如:我如何处理这个问题?@EhsanSajjad你的页面上有多少锚定链接,如果你是专门为菜单说话的,那么你可以在MVC中设置安全微调菜单。但是如果你说的是整个页面上的随机链接,那么我恐怕你要么使用自定义帮助器,要么使用条件。如果这个要求是显示/隐藏表格数据上的一些链接,那么我只需要使用Html Helper,因为它很容易维护。你能分享一些我需要在我的页面上隐藏一些随机链接的示例代码吗,我已经编写了自定义操作过滤器,用户可以查看该页面,但要求是隐藏它,如果它不在其内部rights@EhsanSajjad您可以将这些锚定标记更改为自定义RoleActionLink(),如上图所示,对吗?我是这样写的:我可以编写自定义Url扩展吗?如果可以,如何编写?可能的重复
public static class Html
{
    public static string RoleActionLink(this HtmlHelper html, string role, string linkText, string actionName, string controllerName)
    {
        return html.ViewContext.HttpContext.User.IsInRole(role)
            ? html.ActionLink(linkText, actionName, controllerName)
            : String.Empty;
    }
}