【问题标题】:Why is ServiceSecurityContext.Current null in an MVC Controller?为什么 MVC 控制器中的 ServiceSecurityContext.Current 为空?
【发布时间】:2013-01-23 22:20:44
【问题描述】:

我有一个 ASP.NET MVC 4 项目,它在 Web.config 中使用 Windows 身份验证,如下所示:

<system.web>
    <authentication mode="Windows" />
</system.web>

但是,如果我从 Controller 方法中调查 ServiceSecurityContext.Current,则它为空。由于我使用的是 Windows 身份验证,它不应该包含用户的身份验证信息吗?

我试图弄清楚这一点的原因是因为我想知道 CredentialCache.DefaultNetworkCredentials 从控制器方法中使用的凭据。根据我通过阅读MSDN article on the property 收集到的信息,它使用当前安全上下文的凭据......它为空。

感谢您的帮助!

【问题讨论】:

    标签: asp.net-mvc-4 windows-authentication


    【解决方案1】:

    ServiceContext 类旨在用于 WCF 服务内部。它与 ASP.NET MVC 无关。

    尝试在 ASP.NET MVC 应用程序中使用 ServiceContext.Current 就像尝试在控制台应用程序中使用 HttpContext.Current => 你会得到 NULL。

    我试图弄清楚这一点的原因是因为我想 知道凭据 CredentialCache.DefaultNetworkCredentials 是什么 使用控制器方法

    那么您正在寻找User.Identity.Name 属性:

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

    【讨论】:

    • 太棒了,谢谢!我希望 MSDN 文章当时指向 User.Identity.Name —— 它提到的只是我看到的“当前安全上下文”,这就是我坚持这一点的原因。
    • 你确定它等于 User.Identity.Name 而不是 WindowsIdentity.GetCurrent().Name?我注意到使用 ASP.NET 模拟时只有 WindowsIdentity.GetCurrent().Name 会发生变化。 User.Identity.Name 始终等于客户端的用户名
    猜你喜欢
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多