我在这里查看@ 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操作中执行相同的检查。
答案 0 :(得分:4)
在ASP.NET MVC中,HTML辅助方法只是现有HtmlHelper和AjaxHelper
类的extension methods。一旦你理解了扩展方法在.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
)
答案 1 :(得分: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();
}