2

我在这里创建@Html.ActionLink 助手我检查用户的权限。如果是,我会显示此链接,否则不会。现在的问题是@Ajax.ActionLink 我可以为 Ajax.ActionLink 做助手吗?我制作自定义助手来检查权限。它适用于 html.actionlink 助手。我如何检查 ajax 操作中的权限?

 public static IHtmlString CustomActionLink(this HtmlHelper htmlHelper, int userId, string reqController, string reqAction,  string linkText,int reqActionId = 0)
    {

        bool isAllowed = checkPermission(userId, reqController, reqAction, reqActionId);
        if (isAllowed == false)
        {
            return MvcHtmlString.Empty;
        }
        return htmlHelper.ActionLink(linkText, reqAction, new { id =reqActionId });
    }

我想在 Ajax Actions 中做同样的检查。

4

2 回答 2

4

在 ASP.NET MVC 中,HTML 帮助器方法只是现有 HtmlHelper 和类的扩展方法。AjaxHelper一旦您了解了 .NET 中的扩展方法是什么以及它是如何工作的,那么将这个概念应用到类中就不难了AjaxHelper

public static IHtmlString CustomAjaxActionLink(
    this AjaxHelper ajaxHelper, 
    AjaxOptions ajaxOptions,
    int userId, 
    string reqController, 
    string reqAction,  
    string linkText,
    int reqActionId = 0
)
{
    bool isAllowed = checkPermission(userId, reqController, reqAction, reqActionId);
    if (!isAllowed)
    {
        return MvcHtmlString.Empty;
    }

    return ajaxHelper.ActionLink(
        linkText, 
        reqAction, 
        new { id = reqActionId }, 
        ajaxOptions
    );
}

在您的视图中,只需使用此自定义帮助器(当然,在将声明包含类的命名空间纳入范围之后):

@Ajax.CustomAjaxActionLink(
    new AjaxOptions { UpdateTargetId = "foo" },
    123,
    "SomeController",
    "SomeAction",
    "click me and get a surprise!",
    456
)
于 2012-07-02T08:44:29.807 回答
0

使用 AuthorizeAttribute 怎么样?

public class AuthorizeAdminAttribute : AuthorizeAttribute
    {

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if(!AppSecurity.Instance.IsUserInRoles(filterContext.HttpContext.User, AdminGroups))
            {
                HandleUnauthorizedRequest(filterContext);
            }
            base.OnAuthorization(filterContext);
        }
    }

在你的控制器中你可以使用类似的东西:

[AuthorizeAdmin]
        public ActionResult Index()
        {
            return View();
        }
于 2012-10-23T07:07:06.353 回答