You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

集成测试中如何设置HttpContext的api-version供ActionFilter读取

问题背景

现有Stack Overflow平台上的同类相似回答均不适用于当前场景,需要实现单元测试中给HttpContext设置API版本相关数据的诉求,但账号声望不足无法在对应回答下发表评论。
测试存在明确约束:

  • 测试过程中无法使用Mock对象
  • 现有测试逻辑已直接使用真实的HttpContext实例
  • 仅需要完成HttpContext的api-version属性设置,以便后续从ActionExecutedContext中读取该版本值
已尝试实现

目前已尝试通过QueryString传入api-version参数,相关代码如下:

  1. 测试文件中构建HttpContext的代码
var httpContext = new DefaultHttpContext
{
    RequestServices = this.ServiceProviderBuilder.Build(regions).Object
};

QueryBuilder queryBuilder = new QueryBuilder();
queryBuilder.Add("api-version", serviceVersion.GetDescription());
httpContext.Request.QueryString = queryBuilder.ToQueryString();

构建完成的httpContext实例会被赋值给被测控制器使用的ControllerContext。

  1. 调用控制器方法时构建执行上下文的代码
var context = new ActionExecutedContext(
    new ActionContext
    {
        HttpContext = myController.HttpContext,
        RouteData = new RouteData(),
        ActionDescriptor = new ActionDescriptor()
    },
    new List<IFilterMetadata>(),
    myController);

IActionResult result = await myController.GetInfoAsync()
  1. 自定义ActionFilterAttribute中的版本读取逻辑
/// <inheritdoc />
public override void OnActionExecuted(ActionExecutedContext context)
{
    // 后续业务逻辑需要使用该requestedApiVersion
    ApiVersion requestedApiVersion = context.HttpContext.GetRequestedApiVersion();
}
当前问题

上述通过QueryString添加api-version的方式,无法让GetRequestedApiVersion()方法正确获取到API版本值,需要可行的解决方案。

内容的提问来源于stack exchange,提问作者subzero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 14:57:18