我在MVC4 / ASP.NET Web Api中实现了一项服务。当系统停机进行维护时,我想向客户端返回自定义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 :(得分:2)
事实证明你必须配置http错误才能通过:
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"/>
</system.webServer>
<configuration>
答案 1 :(得分:0)
在Global.asax中注册Application_Error事件并捕获response.statuscode,如果它是503,则在控制器中返回正确的消息
请在以下帖子中查看我的回答
Spring MVC 3: How to provide dynamic content to error page for HTTP 404 errors?