检查 URL 文档 link 是否存在的最佳方法是什么?

Whats is the best way to check URL document link existence?

我需要在不打开 link document/image 的情况下检查 URL 对不同文件的有效性。我在 ASP.net 4.7.2 的验证属性中使用了以下代码。目前的代码如下:(使用jpg可以正常工作)

public override bool IsValid(object DocumentURL)
        {
            try
            {
                string urlLink = (string)DocumentURL;
                WebRequest request = WebRequest.Create(urlLink);
                request.GetResponse();
                return true;
            }
            catch 
            {
                return false;
            }
        }

这适用于图像,但当我将 link 发送到 xls 文件时失败。 错误信息是:

"The request entity's media type 'text/plain' is not supported for this resource"
No mediaTypeFormatter is available to read an object of type 'W_Document_URL' media type 'text/plain'."

我的函数似乎正在尝试打开文档。我只需要检查 URL 文件是否存在,而不需要打开它。 另外,如果我需要将文档限制为图像(jpeg、png、bmp)和 pdf,那么在此函数内限制它的最佳方法是什么?

您可能想要发送 HEAD request。引用 w3.org:

The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.

This method is often used for testing hypertext links for validity, accessibility, and recent modification and for obtaining metainformation about the entity implied by the request without transferring the entity-body itself.

至于实现,也许可以查看 this post,AlexandreJBRodrigues 的示例片段:

HttpClient httpClient = new HttpClient();

HttpRequestMessage request = 
   new HttpRequestMessage(HttpMethod.Head, 
      new Uri("http://iamauri.com"));

HttpResponseMessage response = 
   await httpClient.SendAsync(request);