15

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?

flexxxit
  • 2,440
  • 5
  • 42
  • 69

3 Answers3

29
var mvcContext = context.Resource as AuthorizationFilterContext;
var descriptor = mvcContext?.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
    var actionName = descriptor.ActionName;
    var ctrlName = descriptor.ControllerName;      
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
adem caglin
  • 22,700
  • 10
  • 58
  • 78
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;
Carsten
  • 11,287
  • 7
  • 39
  • 62
3

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.

D2TheC
  • 2,203
  • 20
  • 23