asp.net-web-api – 使用自定义授权测试异步Web api方法

我有一个WebApi方法看起来或多或少像这样:

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
}

这似乎在实际应用程序中工作正常,其中自定义IHttpModule在HttpContext.User和Thread.CurrentPrincipal中设置主体.

但是,从单元测试中调用时:

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

用户在等待(即继续)后重置,因此测试失败.在R#8下运行时会发生这种情况,R#7没有发生这种情况.

我的解决方法是在第一次等待之前保存当前的主体,但它只是满足测试运行者需求的黑客.

如何调用我的控制器方法并确保continuation与原始调用具有相同的主体?

解决方法

我通过升级MVC包修复了这个问题.新版本将主体保存在ApiController.RequestContext.Principal中,与Thread.CurrentPrincipal分开,完全避免了问题.

我的新测试代码以:

controller.RequestContext.Principal = principal;

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....