Get controller and action name from AuthorizationHandlerContext object

Hi I have a custom requirement handler with accepts the AuthorizationHandlerContext context parameter

When i debug, i can see that the context object contains
Context.Resources.ActionDescription.ActionName

But when writing the code i cant go beyond
Context.Resources

Seems the lower levels are not exposed. I want to get the action name and controller name that called the handler. How do i do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

var mvcContext = context.Resource as AuthorizationFilterContext;
var descriptor = mvcContext?.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
    var actionName = descriptor.ActionName;
    var ctrlName = descriptor.ControllerName;      
}

Method 2

After upgrading to dotnet 5, the solution I was successfully using from Carsten above stopped working. The following workaround now works for me:

var routeValues = (context.Resource as HttpContext).Request.RouteValues;
var controllerName = routeValues["controller"].ToString();
var actionName = routeValues["action"].ToString();

Note this should include some null checks etc. the above is a barebones example.

Method 3

Even though the question is tagged for , I wanted to add that the answer by @AdemCaglin does not work for Web API controllers. The following code works for both, API and MVC controllers:

var endpoint = context.Resource as RouteEndpoint;
var descriptor = endpoint?.Metadata?
    .SingleOrDefault(md => md is ControllerActionDescriptor) as ControllerActionDescriptor;

if (descriptor == null)
    throw new InvalidOperationException("Unable to retrieve current action descriptor.");

var controllerName = descriptor.ControllerName;
var actionName = descriptor.ActionName;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x