4

我有一个在 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() - 不走运

4

2 回答 2

2

事实证明,您必须配置 http 错误才能通过:

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough"/>
  </system.webServer>
<configuration>
于 2012-05-22T13:19:25.067 回答
0

在 Global.asax 中注册一个 Application_Error 事件并捕获 response.statuscode ,如果是 503 则在控制器中返回正确的消息

请在下面的帖子中查看我的回答

Spring MVC 3:如何为 HTTP 404 错误提供动态内容到错误页面?

于 2012-05-18T11:59:38.410 回答