简体   繁体   English

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

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

I am using MVC3, C# and Razor. 我正在使用MVC3,C#和Razor。

I am trying to customise the Authorize attribute. 我正在尝试自定义Authorize属性。

A code snippet: 一个代码片段:

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;
        }

The attribute, when used, would look like: 该属性在使用时将如下所示:

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

It would be very useful to get access to this "Roles" parameter and its values within the custom attribute class, but I cannot see how to do it. 在自定义属性类中访问此“ Roles”参数及其值将非常有用,但是我看不到该怎么做。 There must be a property in the "httpContext" variable, but it escapes me. 在“ httpContext”变量中必须有一个属性,但是它使我无所适从。

Thoughts? 思考?

The syntax of: 语法:

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

uses a named parameter . 使用命名参数 Which is actually a property in the class of the attribute. 这实际上是属性类中的一个属性。 Since your class derives from AuthorizeAttribute , which contains this property : 由于您的类派生自AuthorizeAttribute ,其中包含以下属性

public string Roles { get; set; }

You should be able to use it as an argument in the constructor of AuthorizeCustom . 您应该能够将其用作AuthorizeCustom构造函数中的参数。

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

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