【问题标题】:User.Identity.Name is blankUser.Identity.Name 为空
【发布时间】:2015-08-03 14:48:56
【问题描述】:

我对此进行了大量研究,但找不到解决此问题的方法。

我的 web.config :

  <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">

设置为真。

【问题讨论】:

标签: c# asp.net-mvc-5


【解决方案1】:

您是否在授权范围内工作?换句话说,除非你真的说你想要一个特定的控制器或动作被授权,否则即使用户以前登录过,也不会填写任何内容。例如:

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()
{
    ...

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2013-02-14
    相关资源
    最近更新 更多