如何从客户端Blazor Wasm向服务器端发送`HttpRequestMessage`?

时间:2020-06-19 18:09:55

标签: c# asp.net-core asp.net-core-webapi blazor blazor-webassembly

我有一个ASP.NET Core托管的Blazor WebAssembly项目,该项目的结构为Client,Server和Shared。 我想建立一个解析器类,该类将从控制器接收HttpRequestMessage。我想在运行时使用多个数据库。因此,我正在构建此解析器,它将像这样实例化以下DbContext:

我的startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            ...
            //****** CHANGE DBCONTEXT WHEN HTTPRESPONSEMESSSAGE IS "TEST" HERE ******//
            services
                .AddDbContext<SQLServerDbContext>(options =>
                    options.UseSqlServer(_configuration["ConnectionStrings:SQLServerConnection"]))
                .AddDbContext<SQLiteTestDbContext>(options =>
                    options.UseSqlite(_configuration["ConnectionStrings:SQLiteTestConnection"]))
                .AddScoped<DbContextResolver>()
                .AddScoped<IDbContext>(p =>
                {
                    var resolver = p.GetRequiredService<DbContextResolver>();
                    if (!resolver.IsTest)
                    {
                        return p.GetRequiredService<SQLiteTestDbContext>();  // <--- use this DbContext when DbContextResolver.IsTest = true.
                    }
                    return p.GetRequiredService<SQLServerDbContext>();   // <--- use this DbContext when DbContextResolver.IsTest = false.
                });
            ...
         }

我的DbContextResolver类只有一个公共属性:public bool IsTest { get; set; } 我还构建了此中间件功能,该功能将接收HttpRequestMessage并参考DbContext初始化。

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.Use((context, next) =>
            {
                var resolver = context.RequestServices.GetRequiredService<DbContextResolver>();
                resolver.IsTest = context.Request.Query.ContainsKey("test"); // <--- Getting the HttpResponseMessage and setting therefore the resolver property.
                return next();
            });
            ... 
        }

这里的所有代码都在服务器端应用程序中。 我对ASP.NET Core和Blazor WebAssembly还是很陌生,并且不知道如何从客户端应用程序接收消息。

0 个答案:

没有答案