Вопрос

I am running an integration test with HttpClient and HttpServer (In-Memory).

When the test runs a token handler (message handler) is executed where I add this code just for a quick test:

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));
}

When I debug into the action`s controller constructor I do base.User.Identity.IsAuthenticated and its set to TRUE.

I would have expected that the action is run because the Thread.CurrentPrincipal is set.

Why is it not working?

Это было полезно?

Решение

Thread.CurrentPrincipal is deprecated in Web API v2. Use HttpRequestMessage.GetRequestContext().Principal (both setting and getting)

Другие советы

Whenever you set Thread.CurrentPrincipal, you should set HttpContext.User as well.

Hanselman has a blog post on the subject, and it's also covered in this SO answer. Also note that you may need to force an async yield, as described in this SO answer.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top