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

标签 c# asp.net asp.net-core asp.net-core-3.0 blazor-server-side

我的自定义中间件似乎与我的 Blazor 服务器端页面发生了某种冲突。简短的示例中间件检查 bool 状态,如果为真,则重定向到开箱即用的 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>();
    }
}

在启动文件中配置方法:

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");
    });

}

最佳答案

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

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

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

关于c# - 自定义中间件导致 Blazor 服务器端页面停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466189/

相关文章:

c# - .Net MVC 中带有 AJAX 的嵌套表单

C#:关于接口(interface)、实现和继承的困惑

c# - 如何自定义 ASP.Net Core 模型绑定(bind)错误?

c# - 如何在 TreeView 控件的级别1和级别2中设置不同的样式?

c# - 将 C# 控制台应用程序转换为服务(Main 方法不起作用)

asp.net - 身份服务器 - 不记名 token 身份验证 - 如何跟踪失败的授权?

c# - 如何打开 RadWindow

c# - 将大数据集加载到 c# GridView 中的性能问题

.net - ASP.NET - OpenIdConnect - 重定向 URI 的格式不正确

c# - ASPNetCore - 通过 REST 上传文件