我有一个ASP.NET Core 2.1 MVC应用程序,当发生异常时,我试图返回一个单独的html视图。这样做的原因是,如果有错误,我们不希望Google为我们的SEO注册到错误页面的重定向(我省略了开发设置以清除问题)。
我们的创业公司包含此:
app.UseExceptionHandler("/Error/500"); // this caused a redirect because some of our middleware.
app.UseStatusCodePagesWithReExecute("/error/{0}");
但是我们想防止重定向,因此我们需要更改UseExceptionHandler。我已尝试使用此question的答案,如下所示:
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("sumtin wrong").ConfigureAwait(false);
});
});
但是这会导致页面非常难看而没有任何样式。我们尝试使用的另一个解决方案是创建一个错误处理中间件,但是在这里我们遇到了无法添加视图的相同问题。
如果发生异常,如何在不重定向用户的情况下如何返回样式化视图?
编辑:UseExceptionHandler不会导致重定向,它是由我们某些中间件中的错误引起的。
如果发生异常,如何在不重定向用户的情况下如何返回样式化视图?
您快到了。您可以重写(而不是重定向)路径,然后根据当前路径提供HTML。
假设您的sth-wrong.html
文件夹中有一个样式良好的wwwroot/
页面。更改代码如下:
app.UseExceptionHandler(appBuilder=>
{
// override the current Path
appBuilder.Use(async (ctx, next)=>{
ctx.Request.Path = "/sth-wrong.html";
await next();
});
// let the staticFiles middleware to serve the sth-wrong.html
appBuilder.UseStaticFiles();
});