[英]Custom Middleware is causing Blazor Server-side page to stop working
我的自定義中間件似乎與我的 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 協商 url 也被重定向,因此協商將不起作用。
嘗試以下避免這種情況的代碼:
if (statusCheck && context.Request.Path.Value != "/counter"&& !context.Request.Path.Value.StartsWith("/_blazor"))
{
context.Response.Redirect("/counter");
}
else
{
await _next.Invoke(context);
}
我懷疑這里發生的事情是
"/_blazor?id=token_value"
)。 不幸的是,自定義中間件正在重定向每個請求,因此它最終會阻止應用程序與集線器進行初始連接(觸發一堆控制台錯誤) - 盡管我能夠成功重定向到"/counter"
。 但是由於中間件正在停止 SignalR 連接,它會中斷從客戶端到服務器的連接,這是 Blazor 服務器應用程序所必需的。
我建議將此檢查從中間件移開。 您可以嘗試創建一個可以在應用程序處於維護模式時返回的服務,向Index.razor
組件添加服務調用,然后在必要時呈現“維護模式”組件。
這是舊帖。 但我正在使用 app_offline.htm 頁面來停止 blazor 應用程序
我把它放在根目錄(內容根文件夾)中,只有普通的 html,上面寫着“網站正在維護中”
此頁面將終止所有請求和所有 blazor 集線器連接。
然后,當我更新完我的應用程序后,我將此文件重命名為 app_offline2.htm
意思是“app_offline.htm”是一個特殊的文件名,我的框架和核心使用它來確定應用程序是否可以滿足任何請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.