1

我正在使用 HttpClient 和 HttpServer(内存中)运行集成测试。

当测试运行时,将执行令牌处理程序(消息处理程序),我添加此代码只是为了快速测试:

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
        // other code removed for brevity...

    var principal1 = CreatePrincipal(1, "test");
    Thread.CurrentPrincipal = principal1;

    return await base.SendAsync(request, cancellationToken);
}

[Authorize]
[HttpGet]
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK, _service.Get(id));
}

当我调试操作的控制器构造函数时,我会执行 base.User.Identity.IsAuthenticated 并将其设置为 TRUE。

我本来希望该操作会运行,因为 Thread.CurrentPrincipal 已设置。

为什么它不起作用?

4

2 回答 2

2

Thread.CurrentPrincipal 在 Web API v2 中已弃用。使用 HttpRequestMessage.GetRequestContext().Principal (设置和获取)

于 2014-02-02T22:23:34.460 回答
1

每当你设置Thread.CurrentPrincipal时,你也应该设置HttpContext.User

Hanselman 有一篇关于这个主题的博客文章,这个 SO answer也涵盖了它。另请注意,您可能需要强制async让步,如此 SO answer中所述。

于 2014-02-02T20:09:56.947 回答