Sign-in and Sign-out process in ASP.NET Core MVC – Session 61

Sign-in-Sign-Out-ASPNET-Core-MVC

Signing in and Signing out of an ASP.NET Core MVC web app can seem like a daunting task, but it doesn’t have to be! This blog post is here to make the process easier by walking through step-by-step how to implement this feature. Through this post, you’ll not only learn the necessary coding techniques but also understand more about the Sign-in and Sign-out process overall. By the end, you should have all of the knowledge and confidence to implement Sign-in and Sign-out into your web apps!

Implementing Sign-in in ASP.NET Core MVC

First, we need to inject SignInManager which is in Microsoft.AspNetCore.Identity to process Sign-in and Sign-out users.

Then, we need to add the SignIn Action method with the HttpGet method that returns a View.

Now, we should create a View for this Action Method. For this purpose, we need to create a ViewModel which has Email, Password, and RememberMe properties.

After creating the above ViewModel, we can create our View based on the above ViewModel.

As shown above, the form is passed to the controller with the Post method. Thus we need to create HTTPPost Action Method for the posted data.

As you can see, we used the PasswordSignInAsync method of SignInManager class to process the sign-in procedure. Also, we use the value of the RememberMe property to set the IsPersistant option. If IsPersistnat is set to true, the cookie session would be persistent and the browser keeps the session even after closing the browser.

Implementing Sign-Out In ASP.NET Core

Also, each web app needs a Sign-Out ability. For this purpose, we can add an HtppPost Action method to the controller and use SignInManager class and SignOutAsync method.

Then, we need to add Sign-in and Sign-out options to the main menu.

We use _MainLayout.cshtml, to add the options to the web app as do for Register User in the previous session. Also, as the method of Sign-Out action method is Post, we need to call the action method with a From as you can see.

Dynamic Sign-in & Sign-out Menu in ASP.NET Core

For making the menu dynamic, we need to inject SignInManager into the View or Layout View. For this purpose, we need to add the required namespace to the view as well which is Microsoft.AspNetCore.Identity in this case.

Then, with the IsSignedIn method, we can check whether the user is logged in or not.

If you need more details, watch this session video. Also, to be updated about our coming sessions, follow us on Instagram, Facebook, Telegram, or YouTube. Moreover, you can have access to the list of all sessions HERE and you can download this session source code from our GitHub.

You can download this Session Slides form HERE.

0.00 avg. rating (0% score) - 0 votes

Tags

0 0 votes
Article Rating
guest

0 Comments
Inline Feedbacks
View all comments