Windows authentication in MVC

烈酒焚心 提交于 2019-12-01 06:52:39

Don't try to access any HttpContext related stuff in your controller's constructor. The earliest stage where you should be accessing it is Initialize method or inside the controller actions.

For example:

[Authorize]
public ActionResult Index()
{
    string user = User.Identity.Name;
    ...
}

Also make sure that you have enabled Windows Authentication (NTLM) on your web server.

In solution explorer pane select the Web Project and hit F4. (not right click+properties, thats different)

In properties Pane set:
Windows Authentication: Enable
Anonymous Authentication: Disabled

In Web.config: <authentication mode="Windows"></authentication>

To get Username:

HttpContext.Current.User.Identity.Name OR User.Identity.Name

Run your project, Happy Days!

user2912206

Chaps,

if you are running in IISExpress. Make sure the following setting as below:

In web.config

<authentication mode="Windows"/>
<authorization>
  <deny users="?"/>
</authorization>   

open the projectName.csproj in notepad and correct the follwing settings:

<IISExpressAnonymousAuthentication>disabled</IISExpressAnonymousAuthentication>
<IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>

<UseIIS>True</UseIIS>

Try adding:

<authorization>
  <deny users="?" />
</authorization>

to deny access to anonymous users.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!