【问题标题】:app_offline.htm file being used to take webservice offline - possible to read contents of file?app_offline.htm 文件用于使 web 服务脱机 - 可以读取文件内容吗?
【发布时间】:2012-06-01 05:36:43
【问题描述】:

我正在使用此处所述的 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)

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    归功于 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();
                }
            }
        }
    } 
    

    【讨论】:

    • 谢谢,这很有用。虽然理想情况下,我想使用我的 Web 服务代理类,这将无法使用(因为此时流似乎已被释放)。
    • @MoeSisko 我已经用 wcf 服务和客户端代理进行了测试。它工作正常。这就是我将其发布为答案的原因。
    • 抱歉,我的意思是我使用的是旧式 asmx Web 服务(非 wcf)。我会将您的 anwser 标记为已接受,因为它最符合我的要求。
    【解决方案2】:

    您应该使用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
            }
        } 
    }
    

    【讨论】:

    • 这可能有效,但我无法更改 Web 服务调用代码,只是为了获得此功能。但是 +1 表示尝试。
    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2017-06-24
    相关资源
    最近更新 更多