I have a problem with the following code. I tried to implement a custom action filter with dependency injection to my constructor.
I followed the exact way according to this tutorial, but my custom filter not even being called.
Here is what I have implemented so far:
CustomFilter.cs
public class CustomFilter : IActionFilter
{
private readonly UserManager<Kullanici> _userManager;
public CustomFilter(UserManager<Kullanici> userManager)
{
_userManager = userManager;
}
public void OnActionExecuted(ActionExecutedContext context)
{
var user = _userManager.GetUserAsync(context.HttpContext.User).Result;
if (user.KullaniciTipi != Models.Enums.KullaniciTipi.Mezun)
{
var controller = context.Controller as Controller;
controller.TempData["ErrorMessage"] = "Erişim hakkınız bulunmamaktadır.";
context.HttpContext.Response.Redirect("/");
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
My action method in my controller:
[ServiceFilter(typeof(CustomFilter))]
public async Task<IActionResult> Profil()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
var mezunHesabi = user.MezunHesabi;
ProfilViewModel profilViewModel = new ProfilViewModel();
profilViewModel.MapFromModel(mezunHesabi);
return View(profilViewModel);
}
And my program.cs
file:
builder.Services.AddScoped<CustomFilter>();
Any help is so appreciated.
I expect my custom filter to be called but not being called, I followed all the required steps, what's missing?
CodePudding user response:
Sorry guys, my bad. I should have put my code in OnActionExecuting instead of OnActionExecuted.
public class CustomFilter : IActionFilter
{
private readonly UserManager<Kullanici> _userManager;
public CustomFilter(UserManager<Kullanici> userManager)
{
_userManager = userManager;
}
public void OnActionExecuting(ActionExecutingContext context)
{
var user = _userManager.GetUserAsync(context.HttpContext.User).Result;
if (user.KullaniciTipi != Models.Enums.KullaniciTipi.Mezun)
{
var controller = context.Controller as Controller;
controller.TempData["ErrorMessage"] = "Erişim hakkınız bulunmamaktadır.";
context.Result = new RedirectToActionResult(actionName: "Index", controllerName: "Home", null);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
CodePudding user response:
The custom filter class dont have a constructor. You must call your service otherwise.
Example:
public class CustomFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
var userManager = context.Request.GetDependencyScope().GetService(typeof(UserManager)) as UserManager;
...
}
}
It's a example, I don't know if it's possible to get the userManager that way. In my code i'm using other service to validate users.