C# 我怎样才能赶上 404?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1949610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I catch a 404?
提问by JL.
I have the following code:
我有以下代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;
try
{
request.GetResponse();
}
catch
{
}
How can I catch a specific 404 error? The WebExceptionStatus.ProtocolError can only detect that an error occurred, but not give the exact code of the error.
如何捕获特定的 404 错误?WebExceptionStatus.ProtocolError 只能检测到发生了错误,而不能给出错误的确切代码。
For example:
例如:
catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.ProtocolError)
{
throw ex;
}
}
Is just not useful enough... the protocol exception could be 401, 503, 403, anything really.
只是不够有用……协议异常可能是 401、503、403,任何真的。
采纳答案by Jay Riggs
Use the HttpStatusCode Enumeration
, specifically HttpStatusCode.NotFound
使用HttpStatusCode Enumeration
, 特别是HttpStatusCode.NotFound
Something like:
就像是:
HttpWebResponse errorResponse = we.Response as HttpWebResponse;
if (errorResponse.StatusCode == HttpStatusCode.NotFound) {
//
}
Wherewe
is a WebException
.
哪里we
有WebException
.
回答by mezoid
I think if you catch a WebExceptionthere is some information in there that you can use to determine if it was a 404. That's the only way I know of at the moment...I'd be interested in knowing any others...
我想如果你捕捉到一个WebException有一些信息可以用来确定它是否是 404。这是我目前知道的唯一方法......我有兴趣了解其他人......
catch(WebException e) {
if(e.Status == WebExceptionStatus.ProtocolError) {
var statusCode = (HttpWebResponse)e.Response).StatusCode);
var description = (HttpWebResponse)e.Response).StatusDescription);
}
}
回答by Jonathan S.
Check out this snipit. The GetResponse will throw a WebRequestException. Catch that and you can get the status code from the response.
看看这个 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);
}
this came from http://msdn.microsoft.com/en-us/library/system.net.webexception.status.aspx
这来自http://msdn.microsoft.com/en-us/library/system.net.webexception.status.aspx
回答by Dror
回答by MiffTheFox
I haven't tested this, but it should work
我还没有测试过这个,但它应该可以工作
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;
}
回答by Nick Craver
Catch the proper exception type WebException
:
捕获正确的异常类型WebException
:
try
{
var request = (HttpWebRequest) WebRequest.Create(String.Format("http://www.gravatar.com/avatar/{0}?d=404", hashe));
using(var response = (HttpWebResponse)request.GetResponse())
Response.Write("has avatar");
}
catch(WebException e)
{
if(e.Response.StatusCode == 404)
Response.Write("No avatar");
}
回答by John Saunders
try
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
// Process the stream
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null)
{
var resp = (HttpWebResponse) ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
// Do something
}
else
{
// Do something else
}
}
else
{
// Do something else
}
}
回答by unnknown
For VB.NET folks browsing this, I believe we can catch the exception only if it truly is a 404. Something like:
对于浏览此内容的 VB.NET 人员,我相信只有当它确实是 404 时我们才能捕获异常。例如:
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
回答by craftworkgames
In C# 6 you can use exception filters.
在 C# 6 中,您可以使用异常过滤器。
try
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
{
// Process the stream
}
}
catch(WebException ex) when ((ex.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
{
// handle 404 exceptions
}
catch (WebException ex)
{
// handle other web exceptions
}
回答by Sheo Dayal Singh
when POST or GET data to the server using WebRequest class then the type of exception would be WebException.Below is the code for file not found exception
当使用 WebRequest 类向服务器发送 POST 或 GET 数据时,异常类型将是 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);
}
}