自定义中间件导致 Blazor 服务器端页面停止工作

use*_*480 6 c# asp.net asp.net-core blazor-server-side asp.net-core-3.0

我的自定义中间件似乎与我的 blazor 服务器端页面发生了某种冲突。简短的示例中间件检查 bool 状态,如果 true 重定向到开箱即用的 blazor 模板提供的计数器页面。如果没有将中间件插入管道,当您单击按钮时,计数器页面可以正常工作,但是一旦将中间件放置在管道中,按钮就不再起作用,因为它不会增加计数。我已经将自定义中间件放在 app.UseEndpoints 中间件之前,虽然看起来它放在哪里并不重要,因为无论它的顺序如何,它都不起作用。 为什么我的自定义中间件破坏了 blazor 服务器- 侧页无法正常运行?

中间件:

class CheckMaintenanceStatusMiddleware
{
    private readonly RequestDelegate _next;
    public CheckMaintenanceStatusMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {


        var statusCheck = true;

        if(statusCheck && context.Request.Path.Value != "/counter")
        {
            context.Response.Redirect("/counter");
        }
        else
        {
            await _next.Invoke(context);
        }
    }

}

public static class CheckMaintenanceStatusMiddlewareExtension
{
    public static IApplicationBuilder UseCheckMaintenanceStatus(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CheckMaintenanceStatusMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

启动文件中的配置方法:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{


    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseStaticFiles();


    app.UseCookiePolicy();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseCheckMaintenanceStatus();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
    });

}
Run Code Online (Sandbox Code Playgroud)

Nan*_* Yu 5

使用您的代码,blazor 协商 url 也被重定向,因此协商不起作用。

尝试以下避免这种情况的代码:

if (statusCheck && context.Request.Path.Value != "/counter"&& !context.Request.Path.Value.StartsWith("/_blazor"))
{
    context.Response.Redirect("/counter");
}
else
{
    await _next.Invoke(context);
}
Run Code Online (Sandbox Code Playgroud)