我有一个基于 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/