简体   繁体   中英

Is it possible to bind Route Value to a Custom Attribute's Property in ASP.NET Core Web API?

I've a Custom Attribute which I'm using to authorize the request before it hits the Controller Action, in ASP.NET Core Web API. In the image below, " SecureMethod " is the custom attribute.

在此处输入图片说明

I want to add a property in the Custom Attribute, which I want to bind to one of the Route Values, please refer to the image below: 在此处输入图片说明

I want to bind "userIDs" route-value to one of the Custom Attribute's property ("UserIDs", this is an example attribute ).

Is there any way I can bind the route-value to a custom-attribute's property?

TIA

No, it is not possible.

Attribute parameters are restricted to constant values of the following types:

  • Simple types (bool, byte, char, short, int, long, float, and double)

  • string

  • System.Type

  • enums

  • object (The argument to an attribute parameter of type object must be a constant value of one of the above types.)

  • One-dimensional arrays of any of the above types

You cannot nest attributes and you cannot pass non-constant values to attribute parameter. Even though you can declare an attribute parameter as type object, the actual argument you pass in must still be a constant string, bool, etc (declaring it as an object just means you can use any of these types each time you declare the attribute).

One way you can do this is by passing the name of the route parameter to the attribute, and examining the route data in the attribute itself. For example:

[SecureMethod(PermissionRequired = AccessPermissionEnum.DeleteUsers, UserIdsKey = "userIds")]

Then something like:

public AccessPermissionEnum PermissionRequired { get; set; }
public string UserIdsKey { get; set; }

public override void OnActionExecuting(ActionExecutingContext context)
{
    // Depending on how you pass your userIds to the action, you
    // may need to use something else from context to get the data,
    // but it's all available in there.
    var userIds = context.ActionArguments[UserIdsKey];

    // Do something with the ids.

    base.OnActionExecuting(context);
}

Whilst this works, and in certain places it works really well, you should be aware that the filter now has intimate knowledge of the parameter being passed in. For the most part, this usually doesn't matter so much, but it's an approach you shouldn't use everywhere because it will end up adding a lot of coupling if not used well. It's a useful tool to use every now and then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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