ASP.Net 6自定义WebApplicationFactory抛出异常

2024-02-20

我正在将现有的 ASP.Net 5 Web 应用程序迁移到 ASP.Net 6,并遇到了通过集成测试的最后障碍。

我自定义 WebApplicationFactory 并抛出异常:Changing the host configuration using WebApplicationBuilder.WebHost is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "IntegrationTests");
            builder.ConfigureServices(services => {
                // Create a new service provider.
                var serviceProvider = new ServiceCollection()
                    .AddEntityFrameworkInMemoryDatabase().AddLogging()
                    .BuildServiceProvider();

                // Add a database context (AppDbContext) using an in-memory database for testing.
                services.AddDbContextPool<AppDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryAppDb");
                    options.UseInternalServiceProvider(serviceProvider);
                    options.EnableSensitiveDataLogging();
                    options.EnableDetailedErrors();
                    options.LogTo(Console.WriteLine);
                });

                services.AddDbContextPool<AppIdentityDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryIdentityDb");
                    options.UseInternalServiceProvider(serviceProvider);
                    options.EnableSensitiveDataLogging();
                    options.EnableDetailedErrors();
                    options.LogTo(Console.WriteLine);
                });
                services.AddScoped<SignInManager<AppUser>>();
                services.AddScoped<ILogger<UserRepository>>(provider => {
                    ILoggerFactory loggerFactory = provider.GetRequiredService<ILoggerFactory>();
                    return loggerFactory.CreateLogger<UserRepository>();
                });
                services.AddDistributedMemoryCache();
                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database contexts
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var appDb = scopedServices.GetRequiredService<AppDbContext>();
                    var identityDb = scopedServices.GetRequiredService<AppIdentityDbContext>();
                    var logger = scopedServices.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                    // Ensure the database is created.
                    appDb.Database.EnsureCreated();
                    identityDb.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        SeedData.PopulateTestData(identityDb);
                        SeedData.PopulateTestData(appDb);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, $"An error occurred seeding the " +
                            $"database with test messages. Error: {ex.Message}");
                    }
                }
            });
        }
    }

例外:

  Message: 
    System.NotSupportedException : The content root changed from "C:\Projects\C#\AspNetCoreApi\src\Web.Api\" to "C:\Projects\C#\AspNetCoreApi\test\Web.Api.IntegrationTests\bin\Debug\net6.0\". Changing the host configuration using WebApplicationBuilder.WebHost is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

  Stack Trace: 
    ConfigureWebHostBuilder.UseSetting(String key, String value)
    HostingAbstractionsWebHostBuilderExtensions.UseContentRoot(IWebHostBuilder hostBuilder, String contentRoot)
    Program.<Main>$(String[] args) line 58
    --- End of stack trace from previous location ---
    HostingListener.CreateHost()
    <>c__DisplayClass8_0.<ResolveHostFactory>b__0(String[] args)
    DeferredHostBuilder.Build()
    WebApplicationFactory`1.CreateHost(IHostBuilder builder)
    WebApplicationFactory`1.ConfigureHostBuilder(IHostBuilder hostBuilder)
    WebApplicationFactory`1.EnsureServer()
    WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
    WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers)
    WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
    WebApplicationFactory`1.CreateClient()
    MyControllerIntegrationTests.ctor(CustomWebApplicationFactory`1 factory) line 15

任何建议和见解都值得赞赏。


由于 Program.cs 中的这一行而发生错误:

builder.WebHost.UseContentRoot(Path.GetFullPath(Directory.GetCurrentDirectory())); // Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

我添加这个是因为我想保留args因此我用了WebApplication.CreateBuilder(args)。感谢@davidfowl,我使用了以下代码片段:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    ApplicationName = typeof(Program).Assembly.FullName,
    ContentRootPath = Path.GetFullPath(Directory.GetCurrentDirectory()),
    WebRootPath = "wwwroot",
    Args = args
});

并删除了有问题的代码行。注意builder.WebHost.UseContentRoot每当输入参数与默认值不同时就会抛出异常。就我而言,每当运行集成测试时它都会引发异常,但在正确运行应用程序时不会引发异常。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.Net 6自定义WebApplicationFactory抛出异常 的相关文章

随机推荐

  • 如何删除所有没有任何关系的节点 - neo4j/cypher

    我正在 neo4j 数据库中生成节点 并希望删除那些没有关系的节点 执行此操作的最佳密码指令是什么 Try MATCH n WHERE size n 0 DELETE n
  • 在 Firebase 中存储 id 列表

    我不知道如何用 firebase 解决这个问题 我有用户 每个用户都有帖子 每个帖子都有一个由 firebase 生成的 id 如何将这些 id 存储在用户节点中 我正在使用字符串 连接它们 在我的 js 应用程序中解析它们 基本上将它们视
  • 了解 Go 通道死锁

    package main import fmt time func main p producer for c range p fmt Println c func producer lt chan string ch make chan
  • 如何在Android Studio中制作选择器

    在学习课程时 我被指示为 Button 制作一个 xml 选择器 课程说要在 Eclipse 中制作新的 Android xml 但我使用的是 Android Studio 另外 当我自定义编写代码时 它会给我一个错误 它说 必须声明元素选
  • 如何使用JS下载视频标签?

    我有一个链接 我想从中下载视频
  • uitableview 在 iOS 中删除按钮图像

    我想更改 uitableview 单元格的滑动按钮图像 我已经搜索过了 但没有得到想要的结果 我用过这段代码 void willTransitionToState UITableViewCellStateMask state super w
  • 在一次调用中从多个表中选择

    在我的代码中 我有一个页面 其中包含来自 3 个不同表的信息 为了显示此信息 我进行了 3 个 SQL 选择调用 并将它们合并在一个列表中 以作为模型传递到我的视图 我可以通过一次 SQL 调用来完成此操作吗 数据之间没有任何联系 My c
  • 如何创建特定(R、G、B)颜色的 openCV 图像并获取该颜色名称?

    我需要创建一个填充一些 R G B 颜色的图像 并获得该颜色名称 例如 R G B 黑色或红色等 我们可以用 openCV 做这样的事情吗 如何做 具有静态方法的静态颜色图类 两个答案相结合 只需复制并使用即可 pragma once in
  • 按时间范围删除数据存储中的行

    我有一个 CKAN 数据存储 其中有一个名为 recvTime 的时间戳类型列 即在 datastore create 时使用 timestamp 作为类型 如这个链接所示 https github com telefonicaid fiw
  • 在php中从json_decode()获取值时出错?

    我有一个示例代码 description 2G Network GSM 850 900 1800 1900 3G Network HSDPA 850 900 1700 1900 2100 data json decode descripti
  • haskell中完整的缩进规则集

    从哪里可以获得 Haskell 代码编写的完整缩进规则集 过去的问题与我的以下问题类似 导致我提出上述问题 错误消息背后的原因是什么 parse error on input something 我收到的错误消息 Baby hs 103 2
  • 如何获取 git 中多个项目的任何分支中特定用户的提交列表?

    我在多个 git 项目的多个分支工作 我想获得所有这些项目和分支中特定日期的提交列表 用于时间表目的 虽然我可以为此目的编写实用程序脚本 但我不想重新发明轮子 有没有一种简单的方法可以使用现有的基于 UNIX 的工具或一些 git 高级用户
  • 选择两个 IP 范围之间的记录

    我有一张桌子 里面存放着ID Name Code IPLow IPHigh例如 1 Lucas 804645 192 130 1 1 192 130 1 254 2 Maria 222255 192 168 2 1 192 168 2 25
  • 将类型添加到 std 命名空间

    是否可以接受向std命名空间 例如 我想要一个 TCHAR 友好的字符串 那么以下可以接受吗 include
  • sass 无法编译,文件不可读或找不到

    转换错误 Jekyll Converters Sass 在转换时遇到错误 ng assets css all sass 找不到或无法读取要导入的文件 1 tools tools dir 1号线 这是我每次运行 Jekyll 时都会遇到的错误
  • 根据名称选择列表元素

    我有一个指定的向量列表 表示源自 2 个样本 A 和 B 的事件 l temp lt list SF1 t A c rep 1 10 SF2 t A c rep 9 15 SF1 t B c rep 8 12 l temp SF1 t A
  • 如何在 PDFSharp 中遍历 Pdf 对象树?

    我正在尝试使用 C 中的 PDFSharp 遍历现有 PDF 文档中的 PdfItem 对象树 我想创建一个所有对象的层次结构 类似于 PDF Explorer 示例所做的 但我希望它是一棵树而不是所有对象的平面列表 根节点是 docume
  • 函数模板的 typedef 的最佳替代方案?

    我想做的是这样的 template
  • Rails 5 Action Cable 与 Nginx、Puma 和 Redis 一起部署

    我正在尝试使用 Capistrano 将启用 Action Cable 的应用程序部署到 VPS 我正在使用 Puma Nginx 和 Redis 用于电缆 经过几个障碍后 我能够让它在本地开发环境中运行 我正在使用默认的进程内 cable
  • ASP.Net 6自定义WebApplicationFactory抛出异常

    我正在将现有的 ASP Net 5 Web 应用程序迁移到 ASP Net 6 并遇到了通过集成测试的最后障碍 我自定义 WebApplicationFactory 并抛出异常 Changing the host configuration