问题描述
是否有一种方法可以像在Web窗体中那样在ASP.NET Core 5中的每个页面加载上执行代码?在Web窗体中,我使用了Page_Load()
事件处理程序,但是ASP.NET Core 5中的等效功能是什么?因此,如果我在任何控制器中调用任何动作,它将首先运行我的代码,然后运行动作执行。
我发现了这一点:How can I execute common code for every request?,但是当我尝试它时却遇到了错误。
请有人为我提供清晰的解决方案。
此外,我需要一种从一个位置检查会话的解决方案,而不是在每个控制器中编写“检查会话代码”,而是在登录成功后创建会话,但是什么是检查会话的最佳方法?在所有控制器中,如果为null,则重定向到登录页面?
解决方法
在asp.net核心中,您可以使用 Action filters 替换其中的“ Page_Load”方法 网络表单。
您可以在启动时注册动作过滤器的全局范围,以确保在执行每个动作之前执行动作过滤器。
在您的项目中添加以下动作过滤器:
public class MyActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Do something before the action executes.
if (!context.HttpContext.Request.Path.ToString().Contains("Login"))
{
if (context.HttpContext.Session.GetString("user") == null)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "controller","Login" },{ "action","Index" } });
}
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
然后在startup.cs ConfigureServices 方法中,添加以下代码以将其应用于所有范围:
services.AddControllersWithViews(options =>
{
options.Filters.Add(typeof(MyActionFilter));
});