Cookie Check

I am trying to display a toolbar at the top of the user screen if they are logged in, where they can access their account, etc. If they are not logged in, it will display a form allowing them to log in. I'm not quite sure how to do this using C # and Razor, and keep syntax and compilation errors.

My current form is as follows: I have one file, _siteLayout.cshtml. This saves the toolbar at the top of the screen. It checks the login form to an external database and, if it is authenticated, creates a cookie for the client. The form that I essentially want is

if(user logged in) render account management page else{ render login page } 

Simple, but I have a lot of problems. Here is my code removing the volume for now:

 <body> @using System.Text; @using System.Net.Sockets; @{ if(Request.Cookies["mpUsername"] == null){ //if user is not logged in //some authentication is ran, if passed, isValid is set to true if (isValid) { //login is valid, set cookie HttpCookie cookie = Request.Cookies.Get("mpUsername"); if(cookie == null) { cookie = new HttpCookie("mpUsername"); cookie.Value = username; cookie.Expires = DateTime.Now.AddDays(3); Response.Cookies.Add(cookie); } } else { //login invalid, prompt for pass again <text>Password incorrect, please try again</text> } } } }//end of razor, HTML begins <html> <body> @{ //if cookie is set //if(Request.Cookies["mpUsername"] == null){ } <h2>ACCOUNT MANAGEMENT</h2> @{ } else {//user not logged in, cookie not set } //login form </body> </html> 

What is the best way to do what I want to do? There is obviously a lot more in my actual code of the login page and the account management page, so this is a bit confusing, so I removed them from the above code.

+6
source share
1 answer

This will help you learn about Cookies in ASP.NET using C # .

0
source

Source: https://habr.com/ru/post/908901/


All Articles