c# – HttpWebRequest.GetResponse()失败时如何获取错误信息

问题:

我正在初始化HttpWebRequest,然后检索它的响应。 有时,我得到500(或至少5 ##)错误,但没有描述。 我对两个端点都有控制权,希望接收端能获得更多信息。 例如,我想将异常消息从服务器传递到客户端。 使用HttpWebRequest和HttpWebResponse是否可能?

码:

try
{
    HttpWebRequest webRequest = HttpWebRequest.Create(URL) as HttpWebRequest;
    webRequest.Method = WebRequestMethods.Http.Get;
    webRequest.Credentials = new NetworkCredential(Username, Password);
    webRequest.ContentType = "application/x-www-form-urlencoded";
    using(HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
    {
        if(response.StatusCode == HttpStatusCode.OK)
        {
            // Do stuff with response.GetResponseStream();
        }
    }
}
catch(Exception ex)
{
    ShowError(ex);
    // if the server returns a 500 error than the webRequest.GetResponse() method
    // throws an exception and all I get is "The remote server returned an error: (500)."
}

任何帮助,将不胜感激。

I am initiating an HttpWebRequest and then retrieving it’s response.Occasionally, I get a 500 (or at least 5##) error, but no description.I have control over both endpoints and would like the receiving end to get a little bit more information.For example, I would like to pass the exception message from server to client.Is this possible using HttpWebRequest and HttpWebResponse?Code:Any help with this would be much appreciated.

解决方案:

方案1:

使用HttpWebRequest和HttpWebResponse是否可能?

您可以让您的Web服务器简单地捕获异常文本并将其写入响应的主体,然后将状态代码设置为500。现在,客户端在遇到500错误时将抛出异常,但是您可以读取响应流并获取异常消息。

因此,您可以捕获一个WebException ,如果从服务器返回非200状态代码并读取其主体,则会抛出该异常:

catch (WebException ex)
{
    using (var stream = ex.Response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }
}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached
}

方案2:

尝试检查FTP站点上是否存在文件时遇到了这个问题。 如果文件不存在,则尝试检查其时间戳时将出现错误。 但是我想通过检查错误的类型来确保错误不是其他错误。

WebExceptionResponse属性将是FtpWebResponse类型,可以在其上检查其StatusCode属性以查看遇到的FTP错误

这是我最终得到的代码:

    public static bool FileExists(string host, string username, string password, string filename)
    {
        // create FTP request
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
        request.Credentials = new NetworkCredential(username, password);

        // we want to get date stamp - to see if the file exists
        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            var lastModified = response.LastModified;

            // if we get the last modified date then the file exists
            return true;
        }
        catch (WebException ex)
        {
            var ftpResponse = (FtpWebResponse)ex.Response;

            // if the status code is 'file unavailable' then the file doesn't exist
            // may be different depending upon FTP server software
            if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                return false;
            }

            // some other error - like maybe internet is down
            throw;
        }
    }

方案3:

我遇到了类似的情况:

我试图使用BasicHTTPBinding在使用SOAP服务的HTTP错误中读取原始响应。

但是,使用GetResponseStream()读取响应时,出现错误:

流不可读

因此,这段代码对我有用:

try
{
    response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
    var webException = exception.InnerException as WebException;
    var rawResponse = string.Empty;

    var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
    using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
    using (var reader = new StreamReader(brandNewStream))
        rawResponse = reader.ReadToEnd();
}

方案4:

HttpWebRequest myHttprequest = null;
HttpWebResponse myHttpresponse = null;
myHttpRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpRequest.Method = "POST";
myHttpRequest.ContentType = "application/x-www-form-urlencoded";
myHttpRequest.ContentLength = urinfo.Length;
StreamWriter writer = new StreamWriter(myHttprequest.GetRequestStream());
writer.Write(urinfo);
writer.Close();
myHttpresponse = (HttpWebResponse)myHttpRequest.GetResponse();
if (myHttpresponse.StatusCode == HttpStatusCode.OK)
 {
   //Perform necessary action based on response
 }
myHttpresponse.Close(); 

参考连接:

https://stackoverflow.com/questions/7261986/7261986