I want to write a custom filter which will check whether a user is logged in to my site, and redirect them back to the login page if they aren't.
I want the filter to apply automatically to the page when it loads.
I have tried the solution shown below, but the filter doesn't work at the moment.
Filter Code:
using Microsoft.AspNetCore.Mvc.Filters;
namespace MODS.Filters
{
public class AuthorisationPageFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
System.Diagnostics.Debug.Write("Filter Executed"); //write to debugger to test if working
//add real code here
base.OnActionExecuted(context);
}
}
}
Next, here's the filter attribute applied to the page model:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MODS.Filters;
namespace MODS.Pages.Menus
{
[AuthorisationPageFilter]
public class Admin_MainMenuModel : PageModel
{
public ActionResult Admin_MainMenu()
{
System.Diagnostics.Debug.Write("Function Executed");
return new ViewResult();
}
}
}
I am under the impression that you need to call an action/method on the page for the function to apply when the page loads (please tell me if this is correct), so here is the code calling the Admin_MainMenu
method in the .cshtml page file (in a code block at the top of the razor page):
Model.Admin_MainMenu();
My current thoughts are that either:
1. the filter itself is of the wrong type (could be IPageFilter
instead?)
2. that the way I'm implementing it is wrong (either where I apply it to the
page model, or when I call the method on the page).
Any help is greatly appreciated. Thanks.
[Authorize]
on your PageModel. If not, how are you authenticating users? – Swollen