【问题标题】:Custom CustomAuthenticationAttribute depend parameter in ASP.NET MVCASP.NET MVC 中的自定义 CustomAuthenticationAttribute 依赖参数
【发布时间】:2021-05-17 17:39:38
【问题描述】:

如何为 ASP.NET MVC 5 中的操作创建 CustomAuthenticationAttribute 依赖参数,我的意思是如果我发送到模块 5,这意味着获取数据相关的老师,如果我发送 3 作为模块中的参数,返回学生.我想添加两个权限(学生和教师)以允许用户访问学生或教师或两者。

[CustomAuthentication(PermissionCode = "Student_View")]
public ActionResult Index(int module)
{
}

我有问题是因为CustomAuthentication相关页面代码(我将添加两段代码)student_View和teacher_View

【问题讨论】:

  • 属性是在编译时应用的,因此它们不能根据参数表现不同
  • 那么,有什么解决方案可以解决这个问题,检查权限依赖参数,可以在 Action 中添加验证吗?

标签: c# asp.net-mvc permissions roles custom-authentication


【解决方案1】:

我相信您仍然可以使用传入的AuthorizationContext 访问操作参数,具体取决于您的属性设置方式,执行类似于this 的操作。我继承自 AuthorizeAttribute,但这应该适用于其他类型的属性,只要您可以访问 Request 对象。

您还可以通过将"module" 属性名称传递到属性中来使其动态化:

public class CustomAuthenticationAttribute : AuthorizeAttribute {
    public string ParamName { get; set; }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        if (!string.IsNullOrEmpty(ParamName)) {
            if (filterContext.RequestContext.HttpContext.Request.QueryString[ParamName] != null) { // If using GET
                int module = int.Parse(filterContext.RequestContext.HttpContext.Request.QueryString[ParamName]);

                // Do something with module
            } else if (filterContext.RequestContext.HttpContext.Request.Form[ParamName] != null) { // If using POST (I have not tested Form before myself)
                int module = int.Parse(filterContext.RequestContext.HttpContext.Request.Form[ParamName]);

                // Do something with module
            }
        }
    }
}

然后你会像这样使用它:

[CustomAuthentication(ParamName = "module")]
public ActionResult Index(int module) { }

【讨论】:

  • 感谢您的回答,但我想添加权限代码以允许用户进入模块,例如如果用户添加 Student_View,则表示输入学生,如果添加教师视图,则表示输入教师信息,我希望权限代码将其定义给用户以控制对页面(假页面)的访问,因为它是同一页面
  • 你明白我的意思吗,如果你能帮助我
  • @Sam 不确定我是否关注。请在您的问题中提供更多代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多