21

可能重复:
如何捕获 404?

我想知道用 c# asp.net 捕获 404 错误的正确方法这是我正在使用的代码

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(String.Format("http://www.gravatar.com/avatar/{0}?d=404", hashe));

// execute the request
try
{
    //TODO: test for good connectivity first
    //So it will not update the whole database with bad avatars
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Response.Write("has avatar");
}
catch (Exception ex)
{
    if (ex.ToString().Contains("404"))
    {
         Response.Write("No avatar");
    }
}

此代码有效,但我只想知道这是否最有效。

4

0 回答 0