相关疑难解决方法(0)

如何在ASP.NET MVC 4中获取控制器操作的自定义注释属性?

我正在为ASP.NET MVC中的应用程序使用基于权限的授权系统.为此,我创建了一个自定义授权属性

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    string Roles {get; set;}
    string Permission {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

这样我就可以通过角色或具有注释的特定权限密钥来授权用户

public class UserController : Controller
{
    [MyAuthorization(Roles="ADMIN", Permissions="USER_ADD")]
    public ActionResult Add()

    [MyAuthorization(Roles="ADMIN", Permissions="USER_EDIT")]
    public ActionResult Edit()

    [MyAuthorization(Roles="ADMIN", Permissions="USER_DELETE")]
    public ActionResult Delete()
}
Run Code Online (Sandbox Code Playgroud)

然后我在MyAuthorizationAttribute类中重写具有类似逻辑的AuthorizeCore()方法(伪代码)

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if(user not authenticated)
        return false;

    if(user has any role of Roles)
        return true;

    if(user has any permission of Permissions)
        return true;

    return false;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止工作正常.

现在我需要某种扩展方法,以便我可以在视图页面中动态生成动作URL,该视图页面将根据给定动作的MyAuthorization属性授权逻辑返回动作URL.喜欢

@Url.MyAuthorizedAction("Add", "User")
Run Code Online (Sandbox Code Playgroud)

如果用户具有admin角色或具有"USER_ADD"权限(如操作的属性中所定义),则将URL返回到"User/Add",否则返回空字符串.

但在互联网上搜索了几天后,我无法理解.:(

到目前为止,我只找到了这个"安全感知"动作链接?通过执行操作的所有操作过滤器直到失败为止. …

c# asp.net-mvc razor

10
推荐指数
1
解决办法
2万
查看次数

标签 统计

asp.net-mvc ×1

c# ×1

razor ×1