![](/img/trans.png)
[英]I'm getting a 500 status code response when I update ajax ASP.NET MVC
[英]How to send a Status Code 500 in ASP.Net and still write to the response?
我有一個ASP.Net單文件Web服務(包含IHttpHandler
實現的.ashx
文件),它需要能夠作為具有500個內部服務器錯誤狀態代碼的響應返回錯誤。 這在PHP中是相對簡單的事情:
header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: text/plain");
echo "Unable to connect to database on $dbHost";
ASP.Net(C#)等效應該是:
Context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Context.Response.ContentType = "text/plain";
Context.Response.Write("Unable to connect to database on " + dbHost);
當然,這不能按預期工作; 相反,IIS攔截500狀態代碼,刪除我寫入Response
對象的任何內容,並發送調試信息或自定義錯誤頁面,具體取決於應用程序的配置方式。
我的問題 - 如何抑制此IIS行為並直接從我的IHttpHandler
實現發送錯誤信息?
這個應用程序是PHP的一個端口; 客戶端已經寫好了,所以我基本上堅持這個規范。 錯誤地發送200狀態代碼的錯誤不適合模具。
理想情況下,我需要以編程方式控制行為,因為這是我們要分發的SDK的一部分,而沒有任何“ 編輯此文件 ”和“ 更改此IIS設置 ”補充說明。
謝謝!
編輯 :已排序。 Context.Response.TrySkipIisCustomErrors = true
是票證。 哇。
Context.Response.TrySkipIisCustomErrors = true
我以前使用過以下內容,並且能夠使用Page_Load方法中顯示的代碼在自定義消息中拋出503錯誤。 我在負載均衡器后面使用此頁面作為負載均衡器的ping頁面,以了解服務器是否在服務中。
希望這可以幫助。
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));
}
}
您可能希望設置customErrors頁面(可通過web.config進行配置)。 您可以在Session中的請求中存儲您的內容(或通過替代機制),然后配置asp.net以顯示自定義錯誤頁面,該頁面反過來顯示您的自定義輸出。
但需要注意的是:如果500是由於應用程序的基本問題(即StackOverflowException)引起的,並且您嘗試顯示依賴於asp.net的頁面(即MyCustomErrors.aspx),則可能最終一個循環。
有關更多信息,請查看此頁面 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.