Stack Overflow Asked by fiverbox.com on November 5, 2020
Is there a way to execute a code in every page loading in ASP.Net Core 5 like in Web Forms?
In Web Forms I used the "Page_Load", but what is the equivalent in ASP.Net Core 5?
so if I call any Action in any Controller, it will run my code first, then run the Action execution.
I found this : How can I execute common code for every request?
But when I tried it I got errors.
Please someone provide me with clear solution.
Also I need a solution to check the session from one place, instead of writing the "check session code" in each controller, I create the session after the login is succeed, but what is the best way to check the session in all controllers and if it is null then redirect to login page.
In asp.net core, you can use Action filters to replace the "Page_Load" method in webform.
You can register the global scope of Action filters in the startup to ensure that the Action filters will be executed before each action is executed.
Add the following Action filter in your project :
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.
}
}
Then in startup.cs ConfigureServices method, add following code to apply it to all scope:
services.AddControllersWithViews(options =>
{
options.Filters.Add(typeof(MyActionFilter));
});
Correct answer by Yongqing Yu on November 5, 2020
2 Asked on January 8, 2021 by titatovenaar
1 Asked on January 8, 2021 by jason-sui
0 Asked on January 8, 2021 by stavros-koureas
1 Asked on January 8, 2021 by a-nice-guy
0 Asked on January 8, 2021 by karlos-margaritos
3 Asked on January 8, 2021 by winklerrr
1 Asked on January 8, 2021 by thinkingboutcode
1 Asked on January 7, 2021 by user14781783
1 Asked on January 7, 2021 by thorsten-westheider
1 Asked on January 7, 2021 by hassam-saeed
2 Asked on January 7, 2021
3 Asked on January 7, 2021 by david-vittori
1 Asked on January 7, 2021 by positiveguy
1 Asked on January 7, 2021 by nikhil-ponduri
1 Asked on January 7, 2021 by sara-ree
1 Asked on January 7, 2021 by werner-germn-busch
Get help from others!
Recent Questions
Recent Answers
© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP