ASP.NET Core MVC实现页面超时后显示自定义弹窗错误提示
实现ASP.NET Core MVC页面超时弹窗提示
1. 配置后端请求超时中间件
在Program.cs中配置请求超时策略,设置60秒超时阈值,并自定义超时后的响应逻辑,直接返回触发弹窗的脚本:
var builder = WebApplication.CreateBuilder(args); // 添加MVC服务 builder.Services.AddControllersWithViews(); // 配置全局请求超时策略 builder.Services.AddRequestTimeouts(options => { options.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromSeconds(60), TimeoutResponse = context => { // 判断是MVC页面请求时,输出弹窗脚本 if (!context.Request.Path.StartsWithSegments("/api")) { context.Response.ContentType = "text/html"; return context.Response.WriteAsync(@" <script> alert('该页面加载耗时过长,请稍后重试。'); // 可选:自动刷新当前页 // setTimeout(() => window.location.reload(), 2000); </script> "); } // API请求返回JSON格式错误 context.Response.ContentType = "application/json"; return context.Response.WriteAsync("{\"msg\": \"请求超时,请稍后重试。\"}"); } }; }); var app = builder.Build(); // 启用超时中间件(需放在路由配置之前) app.UseRequestTimeouts(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
2. 前端页面加载超时监控(可选补充)
如果需要监控**整个页面资源加载(含静态资源、接口)**的耗时,可在视图页面(如_Layout.cshtml)中添加前端定时器,主动触发弹窗:
<script> // 启动60秒超时定时器 const loadTimer = setTimeout(() => { alert('该页面加载耗时过长,请稍后重试。'); // 可选:终止未完成的页面加载 window.stop(); }, 60000); // 页面完全加载完成后清除定时器 window.addEventListener('load', () => { clearTimeout(loadTimer); }); </script>
关键说明
- 后端中间件针对服务器端Action执行超时,比如数据库查询、复杂计算耗时超60秒时触发;前端定时器针对页面整体加载流程,覆盖静态资源加载、接口请求等全环节,两者可结合使用。
- 若不想直接输出脚本,也可创建专门的超时提示视图(如
Timeout.cshtml),在TimeoutResponse中通过context.Response.Redirect("/Home/Timeout")跳转,视图内展示弹窗逻辑。
内容的提问来源于stack exchange,提问作者Shubham Khandelwal
相关产品推荐
相关产品推荐

