我的自定义中间件似乎与我的 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/