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

Tre*_*vor 79 c# httpwebrequest httpwebresponse

我正在启动一个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)."
}
Run Code Online (Sandbox Code Playgroud)

任何有关这方面的帮助将非常感激.

Dar*_*rov 139

这可能使用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
}
Run Code Online (Sandbox Code Playgroud)

  • `GetRequestStream` 和 `GetResponse` 可以抛出 ***exceptions*** 吗? (2认同)

Sim*_*ver 7

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

Response物业于WebException将类型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;
        }
    }
Run Code Online (Sandbox Code Playgroud)


Joã*_*elo 5

我遇到过类似的情况:

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

但是,在使用 读取响应时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();
}
Run Code Online (Sandbox Code Playgroud)