简体   繁体   中英

ASP.Net MVC4 User.Identity.Name getting empty even though set authentication mode as 'Windows'

I am working on ASP.Net MVC-4 application. I have to implement windows authentication. I have set authentication mode as 'Windows' in web.config file as shown below.

     <system.web>
          <authentication mode="Windows" />
     </system.web>

In controller I try to get username as below.

    string userName = User.Identity.Name;

but every time I am getting empty value. Please let me know for any suggestions. Thanks in advance.

Windows authentication is performed by IIS to establish our managed code User.Identity . Therefore, you need to enable Windows Authentication in your IIS, and in order to force the user to authenticate before being able to access our application, you need to disable Anonymous Authentication

在此输入图像描述

With the given information, it looks like you've configured your project correctly but haven't actually authenticated the user yet.

First some background. There is a simplified tutorial on asp.net where, in between the lines, the following statement is mentioned:

By default, the ASP.NET Development Web Server executes all pages in the context of the current Windows account (whatever account you used to log into Windows).

This means that when you run your project with F5, it executes everything under your currently logged in user account. However, it isn't yet authenticated for the application and therefor your User.Identity.* is not set yet.

In order to verify if this is the case, you should add the [Authorize] attribute on the first controller (or Action) that is called in you ASP.NET MVC project. Most likely you'll be confronted with a "HTTP Error 401.0 - Unauthorized" exception. In this case, you should enable your webserver to authenticate first. The above mentioned tutorial will help you with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM