Home > Software engineering >  .Net 6.0 AuthorizationContext.Controller equivalent
.Net 6.0 AuthorizationContext.Controller equivalent

Time:09-30

I'm migrating some old ASP.NET MVC 5 code to .NET 6.0 and having some trouble with an AuthorizationFilter that, within its OnAuthorization implementation, accesses the decorated method's controller class instance, like this:

// Get the decorated method's name
string actionName = filterContext.ActionDescriptor.ActionName;

// Get the controller instance and then, its type
Type controllerType = filterContext.Controller.GetType(); 

I just can´t see how I would get the controller instance (or event the method's name) from the AuthorizationFilterContext available in .NET 6.0. Any help?

CodePudding user response:

create new class

public class LogEntry : IAuthorizationFilter
{
 public void OnAuthorization(AuthorizationFilterContext context)
 {

 var controllerActionDescriptor = context.ActionDescriptor as 
        ControllerActionDescriptor;
  
 string controllerName = 
     controllerActionDescriptor?.ControllerName;
            string actionName = 

 controllerActionDescriptor?.ActionName;
        
 }
}

In Program.cs register LogEntry class

builder.Services.AddScoped<LogEntry>();

on controller action method

[ServiceFilter(typeof(LogEntry))]
public IActionResult Index() 
{
   return View();
}

enter image description here

  • Related