代码之家  ›  专栏  ›  技术社区  ›  Alexander

如何通过URL检查Web服务器上是否存在文件?

  •  9
  • Alexander  · 技术社区  · 16 年前

    在我们的应用程序中,我们有一些在线帮助。它的工作原理非常简单:如果用户单击“帮助”按钮,将根据当前语言和帮助上下文生成URL(例如。“ http://example.com/help/ “+[LANG_ID]+”[HELP_CONTEXT]),并在浏览器中调用。

    谢谢你的帮助!

    6 回复  |  直到 9 年前
        1
  •  20
  •   Gavin Miller    16 年前

    您可以使用.NET执行HEAD请求,然后查看响应的状态。

    您的代码看起来像这样(改编自 The Lowly HTTP HEAD Request ):

    // create the request
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    
    // instruct the server to return headers only
    request.Method = "HEAD";
    
    // make the connection
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    
    // get the status code
    HttpStatusCode status = response.StatusCode;
    

    这是一份详细的清单 status codes

        2
  •  2
  •   Streklin    16 年前

    我们是否可以假设您在从中检索帮助页时,正在同一个web服务器上运行web应用程序?如果是,则可以使用Server.MapPath方法与System.IO命名空间中的file.Exists方法一起查找服务器上文件的路径,以确认文件存在。

        3
  •  2
  •   Esko    7 年前

    我自己也有同样的问题,发现这个问题和这里的答案真的很有用。

    但这里的答案是用旧的 WebRequest-class 这有点过时,它对启动器没有异步支持。所以我想用更现代的方式来做 HttpClient . 下面是一个示例,其中包含一个用于检查文件是否存在的小助手类:

    using System.Net.Http;
    using System.Threading.Tasks;
    
    class HttpClientHelper
    {
        private static HttpClient _httpClient;
    
        public static async Task<bool> DoesFileExist(string url)
        {
            if (_httpClient == null)
            {
                _httpClient = new HttpClient();
            }
    
            using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url))
            {
                using (HttpResponseMessage response = await _httpClient.SendAsync(request))
                {
                    return response.StatusCode == System.Net.HttpStatusCode.OK;
                }
            }
        }
    }
    

    用法:

    if (await HttpClientHelper.DoesFileExist("https://www.google.com/favicon.ico"))
    {
        // Yes it does!  
    }
    else
    {
        // No it doesn't!
    }
    
        4
  •  1
  •   nobody    16 年前

        5
  •  1
  •   SecretDeveloper    16 年前

    看一看 HttpWebResponse 班级。你可以这样做:

    string url = "http://example.com/help/" + LANG_ID + HELP_CONTEXT;
    WebRequest request=WebRequest.Create(URL);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusDescription=="OK") 
    {
       // worked
    }
    
        6
  •  0
  •   Antipod    16 年前

    function fetchStatus(address) {
     var client = new XMLHttpRequest();
     client.onreadystatechange = function() {
      // in case of network errors this might not give reliable results
      if(this.readyState == 4)
       returnStatus(this.status);
     }
     client.open("HEAD", address);
     client.send();
    }
    

    非常感谢。

        7
  •  0
  •   Michael Todd    16 年前

    编辑:显然一个很好的方法是HEAD请求。

    推荐文章