如何在c#中找到URL的内容?

Pun*_*ant 2 c# asp.net

我有一个URL.现在我想找出URL的内容.根据URL的内容,我的意思是URL是否包含html页面,视频或图像/照片.如何在asp.net中使用c#执行此操作.

Jim*_*hel 5

最简单的方法是使用以下命令执行HEAD请求HttpWebRequest:

var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "HEAD";
using (var response = (HttpWebResponse)req.GetResponse())
{
    // Here, examine the response headers.
    // In particular response.ContentType
}
Run Code Online (Sandbox Code Playgroud)

在某些情况下,HEAD可能会给您405错误,这意味着服务器不支持HEAD.

在这种情况下,只需执行GET请求(更改req.Method = "GET").这将开始下载页面,但您仍然可以查看内容类型标题.