在ASP.NET Core MVC中,可以使用以下方法来自定义处理页面超时时的错误消息。
services.Configure(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.SlidingExpiration = true;
options.Events = new CookieAuthenticationEvents
{
// 当授权凭据过期时触发
OnRedirectToLogin = context =>
{
// 判断是否是AJAX请求
bool isAjax = context.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (isAjax)
{
// 返回自定义错误消息
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.WriteAsync("登录超时,请重新登录。");
}
else
{
// 重定向到登录页面
context.Response.Redirect(context.RedirectUri);
}
return Task.CompletedTask;
}
};
});
[Authorize]
public class HomeController : Controller
{
// ...
}
$.ajax({
url: '/Home/SomeAction',
type: 'GET',
success: function(response) {
// 处理成功响应
},
error: function(xhr, textStatus, errorThrown) {
if (xhr.status === 401) {
// 显示自定义错误消息
alert(xhr.responseText);
}
else {
// 处理其他错误
}
}
});
通过以上步骤,当页面超时时,如果是AJAX请求,则会返回自定义的错误消息,否则将重定向到登录页面。