Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 597
flexxxit Avatar asked Dec 12 '16 15:12

flexxxit


2 Answers

var mvcContext = context.Resource as AuthorizationFilterContext;
var descriptor = mvcContext?.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
    var actionName = descriptor.ActionName;
    var ctrlName = descriptor.ControllerName;      
}
like image 159
adem caglin Avatar answered Oct 18 '22 12:10

adem caglin


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.

like image 26
D2TheC Avatar answered Oct 18 '22 12:10

D2TheC