Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.User.Identity.Name is returning blank

Tags:

c#

asp.net-mvc

I am trying to figure out why HttpContext.User.Identity.Name is returning blank.

Code

public ActionResult Test()
{
    string username = HttpContext.User.Identity.Name;
    return Content(username);         
}

Am I using this in the wrong context? I am trying to get the user's username.

Web.Config

<authentication mode="Windows" />

IIS

I have enabled Anonymous and nothing else is checked. I am running IIS 6.0.

Is there any type of information I need to add to assist with figuring this out? I am pretty stuck. I checked this question but do I need to set a Cookie to make this work?

like image 992
xivo Avatar asked Apr 12 '26 10:04

xivo


2 Answers

I have enabled Anonymous and nothing else is checked. I am running IIS 6.0.

This means that you won't be prompted to login, so User.Identity.IsAuthenticated will be false and User.Identity.Name will be blank.

Uncheck Anonymous Authentication and check Windows Authentication.

like image 153
jrummell Avatar answered Apr 14 '26 22:04

jrummell


IsAuthenticated returns false, and thus Identity.Name returns empty string because you haven't required authentication for that action. You have to enable Windows Authentication and require authentication for the action. Try requiring that the user be authorized for the action by decorating it with the [Authorize] attribute - which will initiate the authentication negotiation.

[Authorize]
public ActionResult Test()
{
    if(Request.IsAuthenticated)
    {
        string username = HttpContext.User.Identity.Name;
        return Content(username);         
    }
    else 
    {
        return Content("User is not authenticated");
    }
}
like image 20
xdumaine Avatar answered Apr 14 '26 22:04

xdumaine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!