Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我怎么才能赶上404?_C#_.net_Exception Handling_Error Handling_Http Status Code 404 - Fatal编程技术网

C# 我怎么才能赶上404?

C# 我怎么才能赶上404?,c#,.net,exception-handling,error-handling,http-status-code-404,C#,.net,Exception Handling,Error Handling,Http Status Code 404,我有以下代码: HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "HEAD"; request.Credentials = MyCredentialCache; try { request.GetResponse(); } catch { } 如何捕获特定的404错误?WebExceptionStatus.ProtocolError只能检测到发生了错误,但不能给出错误的

我有以下代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;

try
{
    request.GetResponse();
}
catch
{
}
如何捕获特定的404错误?WebExceptionStatus.ProtocolError只能检测到发生了错误,但不能给出错误的确切代码

例如:

catch (WebException ex)
{
    if (ex.Status != WebExceptionStatus.ProtocolError)
    {
        throw ex;
    }
}
只是不够有用。。。协议异常可能是401、503、403,真的可以是任何东西。

我认为如果你捕捉到一个异常,其中有一些信息可以用来确定它是否是404。这是我目前知道的唯一方法…我想知道其他人

catch(WebException e) {
    if(e.Status == WebExceptionStatus.ProtocolError) {
        var statusCode = (HttpWebResponse)e.Response).StatusCode);
        var description = (HttpWebResponse)e.Response).StatusDescription);
    }
}

使用
HttpStatusCode枚举
,特别是
HttpStatusCode.NotFound

比如:

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
  //
}
Try
    httpWebrequest.GetResponse()
Catch we As WebException When we.Response IsNot Nothing _
                              AndAlso TypeOf we.Response Is HttpWebResponse _
                              AndAlso (DirectCast(we.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound)

    ' ...

End Try
其中

we
是一个
WebException

请查看此snipit。GetResponse将引发WebRequestException。捕捉它,您可以从响应中获取状态代码

try {
   // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
     HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

    // Get the associated response for the above request.
     HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
    myHttpWebResponse.Close();
}
catch(WebException e) {
    Console.WriteLine("This program is expected to throw WebException on successful run."+
                        "\n\nException Message :" + e.Message);
    if(e.Status == WebExceptionStatus.ProtocolError) {
        Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
        Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
    }
}
catch(Exception e) {
    Console.WriteLine(e.Message);
}
这来自于

请参见关于响应状态的部分:

...
catch(WebException e) {
  Console.WriteLine("The following error occured : {0}",e.Status);  
}
...

我还没有测试过这个,但它应该可以工作

try
{
    // TODO: Make request.
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError) {
        HttpWebResponse resp = ex.Response as HttpWebResponse;
        if (resp != null && resp.StatusCode == HttpStatusCode.NotFound)
        {
            // TODO: Handle 404 error.
        }
        else
            throw;
    }
    else
        throw;
}

捕获正确的异常类型:


对于浏览这个的VB.NET用户,我相信只有当它真的是404时,我们才能捕捉到异常。比如:

HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
  //
}
Try
    httpWebrequest.GetResponse()
Catch we As WebException When we.Response IsNot Nothing _
                              AndAlso TypeOf we.Response Is HttpWebResponse _
                              AndAlso (DirectCast(we.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound)

    ' ...

End Try
在C#6中,您可以使用


使用WebRequest类向服务器发布或获取数据时,异常类型将为WebException。下面是找不到文件异常的代码

        //Create a web request with the specified URL
            string path = @"http://localhost/test.xml1";
            WebRequest myWebRequest = WebRequest.Create(path);

       //Senda a web request and wait for response.
                try
                {
                    WebResponse objwebResponse = myWebRequest.GetResponse();
                    Stream stream= objwebResponse.GetResponseStream();

                }
                catch (WebException ex) {
                    if (((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.NotFound) {
                        throw new FileNotFoundException(ex.Message);
                    }

                }


哈哈@作为可识别的警察,给每个人一个-1分,因为他们没有在使用块中封装响应。这是一项艰巨的工作,但必须有人去做。OTOH,我几乎没有添加这个答案,因为我似乎在责骂其他人,以使我的答案成为最受欢迎的答案。我实际上投了赞成票,但我只注意到一件事:在你的
捕获
的末尾可能会有一个
抛出
(重新抛出),否则,这只会悄悄地吃掉任何其他类型的
WebException
@John Saunders:为什么你的请求没有一个用法呢?@Joel:
WebRequest
没有实现
IDisposable
@John Saunders我没有在那里与你辩论,但这不是问题,他问了捕捉404的最佳方法。我对他的代码所做的更改仅限于回答问题,使更改尽可能简单明了。@John Saunders:修复,我想“如果这是最有效的”使其适用于问题。在访问
StatusCode
@John Saunders-之前,我必须将
e.Response
转换为
HttpWebResponse
。@John Saunders-我是在修改OP的代码,而不是优化它。@John-也许我只是希望他们复制/粘贴
catch
块,因为我在try中的代码与OP完全相同。你应该完全忽略这个问题,因为OP的代码。@John我们忘了这里是示例代码。这是404的另一种方式,而不是如何使用GetResponse-1似乎有点苛刻+谢谢你回答这个问题。@John我认为你在评论中指出这一点很好。我看待向下投票的方式是,如果给出的代码不能解决问题。谢谢你取消了否决票。@John-好吧,我把所有的东西都扔掉了,除了渔获量,开心吗?@John Saunders-我非常乐意把它传给MSDN(我从那里复制了样本…)。这段代码的目的是显示StatusCode的使用情况,而不是尽可能的高效。@John Saunders-我只留下了我想显示的部分,只是为了你:-)nnnoooooo!不要捕捉
系统异常
,也不要依赖处理程序中的异常文本!约翰·桑德斯的回答是最完整的。我想人们只是出于怨恨而否决了他。不要使用
throw-ex
,你会生成一个新的异常,调用堆栈为空。只要使用
throw
。我自己总是觉得这很令人沮丧。如果得到格式正确的响应,并且协议错误消息的格式肯定正确,则不应引发异常。该类应允许用户解释结果并相应地采取行动。@在较新的http客户端中,不再为404之类的内容引发JeremyHolovacs异常。“不要对控制流使用异常”似乎没有在构建
WebRequest
的团队中幸存下来,我可以不制作自己的查找列表,从对象中以某种方式获取数字吗?我想要类似的东西:int-httpresponsecode=HttpStatusCode.ToInt()或类似的东西404@BerggreenDK您应该能够只执行int-httpresonsecode=(int)HttpStatusCode.NotFound-1部分解释我古老的下一票:如果出于某种原因,
we.Response
不是
HttpWebResponse
。如果代码希望假定它将始终具有该类型,那么它应该简单地强制转换:
HttpWebResponse errorResponse=(HttpWebResponse)we.Response。如果发生不可能的情况,这将抛出显式的
InvalidCastException
,而不是神秘的
NullReferenceException
。我得到
使用此代码的非静态字段、方法或属性“WebException.Response”
需要对象引用。这是我一直忽略的一个非常酷的特性!我一直在寻找只捕获401的方法,同时让其他方法传递给通用异常处理程序。这就是路!
        //Create a web request with the specified URL
            string path = @"http://localhost/test.xml1";
            WebRequest myWebRequest = WebRequest.Create(path);

       //Senda a web request and wait for response.
                try
                {
                    WebResponse objwebResponse = myWebRequest.GetResponse();
                    Stream stream= objwebResponse.GetResponseStream();

                }
                catch (WebException ex) {
                    if (((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.NotFound) {
                        throw new FileNotFoundException(ex.Message);
                    }

                }