繁体   English   中英

自定义授权属性时如何使用“ Roles”参数

[英]How can I use the “Roles” parameter when Customising the Authorize Attribute

我正在使用MVC3,C#和Razor。

我正在尝试自定义Authorize属性。

一个代码片段:

public class AuthorizeCustomAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authenticated
            return false;
        }

        var user = httpContext.User;
        if (user.IsInRole("Admin")) // This should not be hardcoded, but use the Roles parm somehow. This is the core of my question here.
        {
            return true;
        }

该属性在使用时将如下所示:

[AuthorizeCustom(Roles="Admin,User")]

在自定义属性类中访问此“ Roles”参数及其值将非常有用,但是我看不到该怎么做。 在“ httpContext”变量中必须有一个属性,但是它使我无所适从。

思考?

语法:

[Authorize(Roles = "Admin,User")]

使用命名参数 这实际上是属性类中的一个属性。 由于您的类派生自AuthorizeAttribute ,其中包含以下属性

public string Roles { get; set; }

您应该能够将其用作AuthorizeCustom构造函数中的参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM