【问题标题】:How do you return a custom 503 message?如何返回自定义 503 消息?
【发布时间】:2012-05-22 08:38:47
【问题描述】:

我在 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() - 没有运气

【问题讨论】:

  • 您为什么使用ISerializable?没有它,模型类似乎很好(如果您还删除了[Serializable] 声明)。

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api wcf-web-api http-status-code-503


【解决方案1】:

原来你必须配置http错误才能通过:

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

【讨论】:

    【解决方案2】:

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

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

    Spring MVC 3: How to provide dynamic content to error page for HTTP 404 errors?

    【讨论】:

    • 这种方法看起来更像是一种 hack。
    猜你喜欢
    • 2020-09-08
    • 2023-03-27
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多