asp.net-mvc-4 - Windows 身份验证和 Asp.Net Web API

标签 asp.net-mvc-4 asp.net-web-api windows-authentication

我有一个基于 MVC4 的带有 Windows 身份验证的 Intranet 应用程序。

当我需要在 Controller 中使用 WindowsIdentity 进行授权时,我只使用

 HttpContext.User.Identity

现在我想对一些 Ajax 调用使用新的 Asp.Net WebAPI。

有没有办法像在 MVC Controller 中一样简单地获取 WindowsIdenty 对象?

最佳答案

请不要引用HttpContext从 Controller 。

您可以访问 Controller User 属性是在没有直接引用 HttpContext 的情况下访问身份的方式.

public class MyController : ApiController
{
    public string Get()
    {
         var indenty = this.User.Identity;
    }
}

为什么

Controller User属性提供了一个抽象级别,允许更容易的模拟和单元测试。这种抽象还允许更大的可移植性,例如如果这是 WebApi 自托管,您甚至无法访问 HttpContext .

要阅读有关如何对 User 属性进行单元测试和模拟的更多信息,请阅读 here .有关更多信息:可移植性阅读 here .

关于asp.net-mvc-4 - Windows 身份验证和 Asp.Net Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14873446/

相关文章:

c# - 无法在 WebApi 响应中设置 Content-MD5 header

c# - 使用 Windows 安全连接到 WCF 服务时出错

SQL Server 2008 错误 18452 登录来自不受信任的域,无法与 Windows 身份验证一起使用

css - 无法为 webgrid 列和行设置宽度或高度

javascript - 从同一页面调用两个按钮不起作用

asp.net-web-api - 如何在 ASP.NET Web Api 中设置 swagger basePath?

使用 DNS 的 IIS Windows 身份验证

c# - 计算在 asp.net mvc 中查看的项目数

c# - GetAsync 请求返回空内容

c# - 将应用程序池凭据用于 WebClient 请求