我通过以下方式进行错误处理设置:
启动文件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExceptionHandlerMiddleware>();
app.UseStatusCodePagesWithReExecute("/Error/Index");
//I Added this as a test but it had no effect.
app.Use((context, next) => {
context.SetEndpoint(null);
return next();
});
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = (context) =>
{
context.Context.Response.GetTypedHeaders()
.CacheControl = new CacheControlHeaderValue
{
MaxAge = TimeSpan.FromDays(30)
};
}
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
现在,我通过尝试类似localhost/mynotexistantpage的方法对其进行了测试,并且它可以正常工作,但出现了错误页面。实际上,在大多数情况下,当我对此进行测试时,都会看到错误页面。但是在一种情况下,我没有该页面。
如果您创建后 Action (实际上是任何 Action ),并且需要在其上使用防伪 token 。现在,如果您向该方法提交表单,但是在html中删除了自动生成的防伪 token ,则服务器将以400状态进行响应,并且不会使用我的错误页面。如果您不提供该页面,那么我得到的页面就是浏览器默认的页面。
补充说明:我的异常处理程序甚至没有捕获到此错误。处理程序构造函数如下所示:
public async Task Invoke(HttpContext context)
{
try
{
await _requestDelegate.Invoke(context);
}
catch (Exception exception)
{
HandleExceptionAsync(context, exception);
}
}
为什么会这样?在处理错误时如何解决所有情况?
最佳答案
这实际上是两个问题。第一个问题是错误,可以在这里找到解决方法:
https://github.com/aspnet/AspNetCore/issues/13715#issuecomment-528929683
第二个问题是因为我对防伪 token 具有自动验证功能。这意味着当页面重新执行时,它又是一个帖子,因此反伪造再次失败,因此无法访问我的错误页面。因此,解决方案是在错误 Controller 上添加IgnoreAntiforgeryToken属性。
关于c# - 如何在.net Core 3.0中显示400错误的自定义页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563177/