我想编写一个自定义过滤器,该过滤器将检查用户是否登录到我的网站,如果没有登录,则将他们重定向回登录页面。
我希望过滤器在加载时自动应用于该页面。
我尝试了以下所示的解决方案,但该过滤器目前无法正常工作。
过滤器代码:
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);
}
}
}
接下来,这是应用于页面模型的filter属性:
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();
}
}
}
给我的印象是,您需要调用页面上的操作/方法才能在页面加载时应用该函数(请告诉我这是否正确),因此这里是调用{{1}的代码.cshtml页面文件中的}方法(在razor页面顶部的代码块中):
Admin_MainMenu
我目前的想法是:
1.筛选器本身的类型错误(可以是Model.Admin_MainMenu();
吗?)
2.我实施它的方式是错误的(无论我将其应用于
页面模型,或者当我在页面上调用方法时。
任何帮助将不胜感激。谢谢。
答案 0 :(得分:1)
data "aws_vpc" "vpc" {
filter {
name = "tag:Name"
values = ["${var.old_cluster_fqdn == "" ? "${var.cluster_fqdn}" : "${var.old_cluster_fqdn}"}-vpc"]
}
}
用于MVC(控制器和动作)。对于Razor页面,您必须使用ActionFilterAttribute
(IPageFilter
用于异步实现)。
There are two different filter pipelines for MVC and Razor Pages
Razor Page过滤器IAsyncPageFilter
和IPageFilter
允许Razor Pages在运行Razor Page处理程序之前和之后运行代码。剃刀页面筛选器与ASP.NET Core MVC操作筛选器相似,不同之处在于它们不能应用于单个页面处理程序方法。
答案 1 :(得分:0)
此答案适用于AspNet MVC而不是AspNetCore MVC,但可能对某人有用:
如果用于授权,我将使用AuthorizeAttribute类。
类似这样的东西:
using System.Web.Mvc;
namespace MODS.Filters
{
public class CustomAuthorizeUserAttribute : AuthorizeAttribute
{
// Custom property, such as Admin|User|Anon
public string AccessLevel { get; set; }
// Check to see it the user is authorized
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
System.Diagnostics.Debug.Write("Authorize Executed"); //write to debugger to test if working
// Use Core MVC Security Model
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
// Or use your own method of checking that the user is logged in and authorized. Returns a Boolean value.
return MySecurityHelper.CheckAccessLevel(AccessLevel);
}
// What to do when not authorized
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Error",
action = "NotFound"
})
);
}
}
}
然后使用CustomAuthorizeUser
属性装饰控制器或动作:
using MODS.Filters;
namespace MODS.Pages.Menus
{
[CustomAuthorizeUser(AccessLevel = "Admin")]
public class Admin_MainMenuModel : PageModel
{
public ActionResult Admin_MainMenu()
{
System.Diagnostics.Debug.Write("Function Executed");
return new ViewResult();
}
}
}
希望这会有所帮助!