c# - get roles attribute of controller in OnActionExecuting in mvc -


i want read filter attributes of controller in onactionexecuting method. have written code empty array.

public class basecontroller : controller     {         protected override void onactionexecuting(actionexecutingcontext filtercontext)         {             var getactionname = filtercontext.actiondescriptor.actionname;             var getcontrollername = filtercontext.actiondescriptor.controllerdescriptor.controllername;             var getusername = user.identity.name;             var getuserroles = roles.getrolesforuser(getusername);             foreach (var filter in filtercontext.actiondescriptor.getcustomattributes(typeof(roles), false))             {                 var desiredvalue = filter.tostring();             }            //some business logic here          }     } 

this controller

[authorize(roles = "admin")]     public class admincontroller : basecontroller     {          public actionresult index()         {              return view();         }     } 

i want list of allowed roles executing controller.

you can use getfilterattributes method of actiondescriptor or controllerdescriptor:

    protected override void onactionexecuting(actionexecutingcontext filtercontext)     {         var filters = new list<filterattribute>();         filters.addrange(filtercontext.actiondescriptor.getfilterattributes(false));         filters.addrange(filtercontext.actiondescriptor.controllerdescriptor.getfilterattributes(false));         var roles = filters.oftype<authorizeattribute>().select(f => f.roles);         ...     } 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -