How to send a Status Code 500 in ASP.Net and still write to the response?

微笑、不失礼 提交于 2019-11-27 11:31:58

Context.Response.TrySkipIisCustomErrors = true

I have used the following in the past and been able to throw a 503 error with a custom message using the code shown below in the Page_Load method. I use this page behind a load balancer as the ping page for the load balancer to know if a server is in service or not.

Hope this helps.

        protected void Page_Load(object sender, System.EventArgs e)
    {
        if (Common.CheckDatabaseConnection())
        {
            this.LiteralMachineName.Text = Environment.MachineName; 
        }
        else
        {
            Response.ClearHeaders();
            Response.ClearContent(); 
            Response.Status = "503 ServiceUnavailable";
            Response.StatusCode = 503;
            Response.StatusDescription= "An error has occurred";
            Response.Flush();
            throw new HttpException(503,string.Format("An internal error occurred in the Application on {0}",Environment.MachineName));  
        }
    }

You may wish to set a customErrors page (configurable via the web.config). You can store your content across requests in Session (or via an alternative mechanism) then have asp.net configured to display the custom error page which in-turn displays your custom output.

A word of caution, though: If the 500 is being caused because of a fundamental problem with the application (i.e. StackOverflowException) and you try to display a page that depends on asp.net (i.e. MyCustomErrors.aspx), you may end up in a loop.

For more information, check out this page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!