Windows Authentication - Getting current user name

无人久伴 提交于 2020-01-01 09:39:09

问题


In my MVC application I want to render a table in a cshtml file, if the current log in user is some x person. I am using windows authentication and I have made the following changes in web.config file.

<authentication mode="Windows">
      </authentication>

And in my controller when I am trying to access the current user name I am not getting any user name. I am trying the following:

ViewBag.LogInUserName = Request.RequestContext.HttpContext.User.Identity.Name;

This above line was working before. But I don't know whats wrong now. Also I have hosted my application on IIS now.


回答1:


You need to put the [Authorize] attribute on your controller.

You can use User.Identity.Name in your controllers.

[Authorize]
public class YourController : Controller
{

    public ActionResult SomeAction()
    {
        var userName = User.Identity.Name;
    }
}



回答2:


Take a look at the web project's properties, in particular:

  1. Anonymous Authentication - Set to "Disabled"
  2. Windows Authentication - Set to "Enabled"

By default these are set to the opposite of what you're probably looking for.

(Image sourced from MSDN)




回答3:


A little bit late, but this may serve others in the future.

I had the same problem once after deploying my site to a new IIS server, and the anonymous authentication was enabled, so make sure that anonymous authentication is disabled and it should work.



来源:https://stackoverflow.com/questions/8968254/windows-authentication-getting-current-user-name

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