0

我正在使用此处所述的 app_offline.htm 文件: http : //weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx 使旧的 asmx Web 服务脱机。

一切正常,客户端收到 HTTP 503 异常,如:

Exception : System.Net.WebException
The request failed with HTTP status 503: Service Unavailable.
Source : System.Web.Services
Stack trace :
   at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
   at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 

我的问题:客户端应用程序是否可以读取 app_offline.htm 文件的内容,该文件将被返回?该文件中的基本 HTML 包含有用的文本,例如:“应用程序当前正在进行维护”。我可以看到这个文件的内容在使用 Fiddler 的响应中返回。

能够解析此 html 响应以向用户提供更多信息会很有用。(即,因此可以区分由于系统维护导致的 503 错误,以及由于系统过载等导致的其他 503)。

编辑:BluesRockAddict 的反应听起来不错,但此时流似乎不可用。例如:

            // wex is the caught System.Net.WebException 
            System.Net.WebResponse resp = wex.Response;


            byte[] buff =  new byte[512];
            Stream st = resp.GetResponseStream();

            int count = st.Read(buff, 0, 512);  

上面尝试读取流的最后一行给出:

Exception : System.ObjectDisposedException
Cannot access a closed Stream.
Source : mscorlib
Stack trace :
   at System.IO.__Error.StreamIsClosed()
   at System.IO.MemoryStream.Read(Byte[] buffer, Int32 offset, Int32 count)
4

2 回答 2

2

归功于 BluesRockAddict,添加到他的答案中,这就是您可以阅读 html 页面内容的方式。

catch (WebException ex)
{
    if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
    {
        using (Stream stream = ex.Response.GetResponseStream())
        {
            using(StreamReader reader = new StreamReader(stream))
            {
                var message = reader.ReadToEnd();
            }
        }
    }
} 
于 2012-06-01T08:38:43.250 回答
1

您应该使用WebException.Response来检索消息:

using (WebClient wc = new WebClient())
{
    try
    {
        string content = wc.DownloadString(url);
    }
    catch (WebException ex)
    {
        if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
        {
            message = ex.Response
        }
    } 
}
于 2012-06-01T05:56:10.037 回答