【问题标题】:How to customize default error pages in azure web app for linux?如何在 azure web app for linux 中自定义默认错误页面?
【发布时间】:2020-03-21 05:22:37
【问题描述】:

我在 Azure Web 应用程序中托管了 .NET core 3.1.1 LTS 应用程序 for linux?如何自定义默认错误页面,例如 1. 502 2 应用服务停止时的错误页面。 3 从 Visual Studio、VS 代码/FTP 发布应用程序时出现错误页面

【问题讨论】:

标签: azure azure-web-app-service azure-app-service-plans


【解决方案1】:

我找到了一个关于创建应用程序网关自定义错误页面的文档,也许它对你有好处。 custom error pages 如何在代码中创建自定义错误页面。

我们也可以通过代码处理。这是我的建议。

500之类的错误,我们可以通过过滤器处理

public class ErrorPageFilter : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext context)
    {
        if (context.HttpContext.Response.StatusCode == 500)
        {
            context.HttpContext.Response.Redirect("error/500");
        }
        base.OnResultExecuted(context);
        }
}

[ErrorPageFilter]
public abstract class PageController
{}

对于.netcore mvc项目,还自带了创建时错误页面的管道处理。

在startup.cs中,

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        //dev env show error page
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            //prod env show custom page
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
}

//In HomeController has this function,
//You just replace cshtml file by you want
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore =     true)]
public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ??     HttpContext.TraceIdentifier });
}

404之类的错误,我们可以

在startup.cs文件中找到configure函数,然后添加如下代码,

  app.UseStatusCodePagesWithReExecute("/error/{0}");

然后添加错误控制器,

public class ErrorController : Controller
{
        /// <summary>
        /// In content in {0} is error code
        /// </summary>
        /// <returns></returns>
        [Route("/error/{0}")]
        public IActionResult Page()
        {
            //Jump to 404 error page
            if (Response.StatusCode == 404)
            {
                return View("/views/error/notfound.cshtml");
            }
            return View();
        }
}

注意,如果使用 ErroeController(处理 404 错误),请不要使用 app.UseExceptionHandler("/Home/Error"), 你只需要在 Controller 中处理错误。

【讨论】:

  • 记录指出使用应用程序网关。不使用应用程序网关如何做到这一点?
  • 好的,我知道了。我会修改我的答案来帮助你。关于如何在.net核心程序中自定义错误页面。
  • 你可以试试,如果它有效,请告诉我。@Bharat
  • 按照您的建议,使用状态代码页可以部分解决 404、403 的问题。但我仍然没有弄清楚如何自定义 502 等 azure 默认页面,从 vs web deploy 发布应用时出错
  • 您是否尝试使用这种方式使用类似context.HttpContext.Response.StatusCode == 500 的代码?您可以修改StatusCode并跟踪它。
猜你喜欢
  • 1970-01-01
  • 2022-03-07
  • 2019-04-03
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2011-10-27
相关资源
最近更新 更多