3

我有一個在MVC4/ASP.NET Web Api中實現的服務。我想在系統關閉以進行維護時向客戶返回自定義503消息。如何返回自定義503消息?

我有以下代碼:

public class ServiceController : ApiController 
    { 
     public HttpResponseMessage<ServiceUnavailableModel> Get() 
     { 
      return new HttpResponseMessage<ServiceUnavailableModel>(new ServiceUnavailableModel(), HttpStatusCode.ServiceUnavailable); 
     } 
    } 

我的模型看起來是這樣的:

[Serializable] 
    public class ServiceUnavailableModel : ISerializable 
    { 
     public ServiceUnavailableModel() 
     { 
      this.Message = Resources.SDE_SERVICE_UNAVAILABLE; 
      this.Detail = Resources.SDE_SERVICE_REQUESTED_CURRENTLY; 
      this.Code = (int)System.Net.HttpStatusCode.ServiceUnavailable; 
     } 

     public string Message { get; set; } 
     public string Detail { get; set; } 
     public int Code { get; set; } 

     public virtual void GetObjectData(SerializationInfo info, StreamingContext context) 
     { 
      info.AddValue("Message", this.Message); 
      info.AddValue("Detail", this.Detail); 
      info.AddValue("Code", this.Code); 
     } 

    } 

這簡直是什麼一堆我目前的API的客戶的期望。但是,當我執行這個動作,我得到以下結果:

HTTP/1.1 503 Service Unavailable 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: text/html 
Expires: -1 
Server: Microsoft-IIS/7.5 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Mon, 14 May 2012 20:22:39 GMT 
Content-Length: 200 

The service is unavailable.The service you requested is currently 
unavailable or undergoing maintenance. We will have the service back 
up and running shortly. Thank you for your patience.","Code":503} 

注意它如何出現,我的反應是部分系列化。是什麼賦予了?

PS。我試過Response.Clear()和Response.ClearContent() - 沒有運氣

+0

爲什麼你使用'ISerializable'?沒有它的模型類似乎很好(如果你還刪除'[Serializable]'聲明)。 – carlosfigueira

回答

1

事實證明,您必須配置HTTP錯誤通過:

<configuration> 
    <system.webServer> 
    <httpErrors existingResponse="PassThrough"/> 
    </system.webServer> 
<configuration>