How to check user is "logged in"?

C#asp.netForms Authentication

C# Problem Overview


I am using form authentication with below method in my ASP.NET application

FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);

How do I check whether user is logged in or not? And how can I get the user name of a logged in user?

C# Solutions


Solution 1 - C#

I managed to find the correct one. It is below.

bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated

EDIT

The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.

bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated

Solution 2 - C#

The simplest way:

if (Request.IsAuthenticated) ...

Solution 3 - C#

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

Solution 4 - C#

Easiest way to check if they are authenticated is Request.User.IsAuthenticated I think (from memory)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlueBirdView Question on Stackoverflow
Solution 1 - C#BlueBirdView Answer on Stackoverflow
Solution 2 - C#KeithView Answer on Stackoverflow
Solution 3 - C#YangaView Answer on Stackoverflow
Solution 4 - C#isNaN1247View Answer on Stackoverflow