1. Create a new. NET Core MVC Project
2. Add a class MyAttribute below the Models folder, which is designed to hold the attributes we define
Here, I only wrote checkloginattribute to verify the login situation.
usingMicrosoft.AspNetCore.Http;usingMICROSOFT.ASPNETCORE.MVC;usingMicrosoft.AspNetCore.Mvc.Filters;usingSystem;namespaceattributestudy.models{ Public classMyAttribute {} Public classCheckloginattribute:attribute,iactionfilter { Public voidOnActionExecuted (ActionExecutedContext context)//execute after method execution { } Public voidOnActionExecuting (ActionExecutingContext context)//execute before method execution { if(Context. HttpContext.Session.GetString ("LoginName")==NULL) {context. Result=NewRedirectresult (" Contact");//If the session does not exist, the login is unsuccessful and jumps to the contact page}Else{//Otherwise, do not operate. } } }}
Because this is not a controller, we have to use the session to invoke the context of the injection.
Also, using sesion in. Net core has to add a configuration to startup
Configureservices add services below. Addsession (); Add apps below Configure . Usesession ();
. Net core uses feature attribute to verify session login status