User.Identity.Name is blank

本文关键字:blank is Name Identity User | 更新日期: 2023-09-27 18:06:18

我对此做了大量的研究,但没有找到解决这个问题的方法。

我的网页。配置:

  <system.web>
    <compilation debug="true" targetFramework="4.5.1"/>
    <httpRuntime targetFramework="4.5.2"/>
    <authentication mode="Windows"/>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

和出于某种原因

string User = User.Identity.Name;

总是空的。

IIS Windows身份验证是唯一启用的选项。

我试过了

[Authorize]

相同的结果。

我检查了IIS配置文件以确保

  <windowsAuthentication enabled="true">

User.Identity.Name is blank

您是否在授权的上下文中工作?换句话说,除非您确实说要授权特定的控制器或操作,否则即使用户以前登录过,也不会填充任何内容。例如:

public ActionResult Foo()
{
    var user = User.Identity.Name; // null
}

,

[Authorize]
public ActionResult Foo()
{
   var user = User.Identity.Name; // WIN
}

如果您仍然需要允许匿名访问的操作,只需添加[AllowAnonymous]:

[Authorize]
[AllowAnonymous]
public ActionResult Foo()
{
    ...