Testing async web api methods with user authorization

I have a WebApi method that looks something like this:

public async Task<HttpResponseMessage> Get(Guid id)
{
    var foo = await Store.GetFooAsync(id);
    if (foo.BelongsTo != User.Identity.Name)
        throw new HttpResponseException(HttpStatusCode.Forbidden);
    //return foo here
}

This seems to work just fine in a real application, where the user IHttpModulesets the principal to both HttpContext.User, and Thread.CurrentPrincipal.

However, when called from unit test:

Thread.CurrentPrincipal = principal;
var response = controller.Get(id).Result;

Userreset after await(i.e. continue), so the test fails. This happens when working under R # 8, and this did not happen with R # 7.

My workaround was to keep the current principal until the first wait, but it’s just a hack to satisfy the test’s needs.

How can I call my controller method and make sure that the continuations have the same principle as the original call?

+4
2

, MVC. ApiController.RequestContext.Principal, Thread.CurrentPrincipal, .

:

controller.RequestContext.Principal = principal;
+1

HttpContext.Current.Use Thread.Principal.

: Request.LogonUserIdentity Request.RequestContext.HttpContext.User.

async/await , , . , ASP.NET , await. , await, ThreadPool, CurrentPrincipal - .

, .NET- " .

0

All Articles