Home > Blockchain >  Making pages that can be displayed only if logged in - ASP.NET Core MVC
Making pages that can be displayed only if logged in - ASP.NET Core MVC

Time:06-12

I have always been programming with ASP.NET Web Forms. Everything was simpler but now for having better performance and modern software, I decided to switch to ASP.NET MVC.

I managed to understand most of the concepts but due to lack of Page Lifecyle in MVC, I am having troubles verifying whether the user has logged in.

Let me give you an example:

In ASP.NET Web Forms, I use to make a login page where if the user exists and has given proper credentials, the program would create a Session variable like this: Session["UserID"] = 3;

And when the user is navigated to his or her account page, the a code like the one below would check if the user is logged in:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(Session["UserID"]==null)
        {
             Response.Redirect("/login.aspx");
        }
    }

how to make the same thing in MVC?

CodePudding user response:

Add [Authorize] above your function. You could add it above your controller if you want all the functions to be available to logged-in users.

If you do this, don't forget to add app.UseAuthorization(); in your Program.cs file

Tell me if this helps ^^

  • Related