【问题标题】:WebRequest Checking If File Exisits on Remote Server Always Returning True Due to 404 RedirectWebRequest 检查远程服务器上是否存在文件由于 404 重定向而总是返回 True
【发布时间】:2014-09-27 02:17:21
【问题描述】:

我的所有文件都有一个文件共享远程服务器。我想在显示它们之前检查它们是否存在。

这很好用,但是当文件不存在时会中断,因为在网站上我有一个自动 404 重定向,因此如果文件不存在,它总是返回状态码 200 或 TRUE 作为网页在它的脑海中确实存在,因为它重定向并呈现。

我该如何解决这个问题?

public bool verifyFile(string filePath)
    {
        bool result = true;
        string Domain = "http://www.SiteName.com/";

        try
        {
            WebRequest webRequest = WebRequest.Create(Domain + filePath);
            webRequest.Timeout = 1200;
            webRequest.Method = "HEAD";

            webRequest.GetResponse();
        }
        catch
        {
            result = false;
        }

        return result;
    }

【问题讨论】:

  • 修复自动重定向?提供实际的 404 代码在许多其他情况下也很有用(例如 SEO 和调试)。
  • 要通过您的代码示例解决您的直接问题,您可以检查响应标头,也许您期望某种 mime 类型,当您收到虚假的 404 响应时可能会有所不同。
  • @Matthew - 你成功了!!通过检查响应的 MimeType 或“ContentType”,如果它命中重定向,它将返回“text/html”。我已经在下面发布了我的修复。

标签: c# validation http-status-code-404 webrequest


【解决方案1】:

@Matthew 提供了正确答案。我需要检查返回的 MimeType。如果它作为网页返回(text/html; charset=utf-8),那么我将返回设置为 false。如果文件确实存在,则 mimetype 将是图像或文档。请参阅下面的更新代码。

public bool verifyFile(string filePath)
    {
        bool result = true;
        string Domain = "http://www.SiteName.com/";

        try
        {
            WebRequest webRequest = WebRequest.Create(Domain + filePath);
            webRequest.Timeout = 1200;
            webRequest.Method = "HEAD";

            WebResponse webResponse = webRequest.GetResponse();

            result = webResponse.ContentType.ToString() == "text/html; charset=utf-8" ? false : true;
        }
        catch
        {
            result = false;
        }

        return result;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 2014-01-31
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 2010-12-12
    相关资源
    最近更新 更多