简体   繁体   中英

How do I get the current Windows logged-in user's username?

I am developing an intranet application using ASP.NET MVC 4. I am using custom forms authentication. When the user accesses the application I want to take the user's Windows logged-in username and check that username in my database. But I don't know how to take that username. I try to take it using the following code:

string CurLoggedInUsername = Environment.UserName;

This gives me the username when I run from Visual Studio, but when I host my application on IIS it gives a weird value. I also tried to use

string CurLoggedInUsername = httpcontext.current.user.identity.name;

but no use. Is there a way to get the user's Windows logged-in username before authentication?

It sounds like you may need to consider mixed-mode authentication. Ie Windows and Forms authentication. The thing is they don't necessarily play well together.

The following article describes the problem and how to overcome it. The thrust of the article centres around how a 401 challenge (Windows authentication) and 302 redirect (forms authentication) are incompatible in > IIS 7 integrated mode and a way to use a couple of forms and HTTP pipeline interception to get at user details. I used the approach successfully for a large public sector client (albeit for a webforms application). I'm sure the principles are the same.

IIS 7.0 Two-Level Authentication with Forms Authentication and Windows Authentication

I forgot to add in the code examples the right place to look for Windows authentication credentials are presented. It's been a while, so I can't remember it off the top of my head.

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