. Net core uses feature attribute to verify session login status

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.