首页 > 解决方案 > 验证不允许 HEAD 时 URL 中是否存在图像

问题描述

在 C# 中使用HttpClient时,我试图在不下载实际图像的情况下验证图像是否存在于给定的 URL 中。这些图像可以来自任何可公开访问的地址。我一直在使用HEAD似乎适用于许多/大多数的 HTTP 动词。谷歌驱动器图像被证明是困难的。

给定一个像这样的公共共享链接: https://drive.google.com/file/d/1oCmOEJp0vk73uYhzDTr2QJeKZOkyIm6v/view?usp=sharing 我可以愉快地使用HEAD, 得到 a200 OK并且它似乎很高兴。但是,这不是图像。这是一个可以下载图像的页面。

稍微麻烦一下,您可以将 URL 更改为此以实际获取图像,这是我真正想要检查的内容: https://drive.google.com/uc?export=download&id=1oCmOEJp0vk73uYhzDTr2QJeKZOkyIm6v

但是,如果HEAD405 MethodNotAllowed URL 确实不存在,您会返回一个404 NotFound

所以我被困在405. HEAD在不允许的情况下,我的下一步是什么(不使用 Google API) ?如果它根本不是,我不能假设它是一个有效的图像404。我检查Content-type以验证它是一个图像,该图像存在此问题范围之外的问题。

标签: google-drive-apidotnet-httpclient

解决方案


HttpClient允许我们发出一个 http 请求,您可以在其中指定您只对标头感兴趣。

诀窍是将HttpCompletionOption 枚举值传递给 theSendAsync或任何其他{HttpVerb}Async方法:

| Enum name           | Value | Description                                                                                                         |
|---------------------|-------|---------------------------------------------------------------------------------------------------------------------|
| ResponseContentRead | 0     | The operation should complete after reading the entire response including the content.                              |
| ResponseHeadersRead | 1     | The operation should complete as soon as a response is available and headers are read. The content is not read yet. |
await client.GetAsync(targetUrlWhichDoesNotSupportHead, HttpCompletionOption.ResponseHeadersRead);

这是一篇深入的文章,详细介绍了此枚举如何更改HttpClient.

相关源码片段:


推荐阅读