Rushabh Verma 0 Newbie Poster

I need to check the validity of the URL to different files without opening the link document/image. I used the below code in ASP.net 4.7.2 in validation attribute. The current code is as follows : (working fine with jpg)

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

This works for images but failed when I sent a link to xls file. The error message is :

       "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'."

This looks like my function is trying to open the document. I need only to check the existence of the URL document but does not need to open it. Also if I need to restrict the documents to images(jpeg,png,bmp) and pdf, what is the best way to limit that inside this function?

Dani AI

Generated

— short, practical approach that avoids downloading whole files and lets you restrict to images/PDFs.

Use an HTTP HEAD request first (it fetches headers only). If the server rejects HEAD (405) or returns a generic/incorrect Content-Type, fall back to a small ranged GET (Range: bytes=0-0 or 0-511) so you only download a few bytes and can inspect headers or magic bytes. Check the HTTP status code (200/206 = exists, 3xx = follow redirects, 4xx/5xx = not available) and then validate the response Content-Type against allowed MIME types (for images and PDF: image/jpeg, image/png, image/bmp, application/pdf). Also validate the URL itself with Uri.TryCreate and limit schemes to http/https to avoid file:// or other risky schemes.

Example pattern (VB.NET, async HttpClient):

' reuse a single HttpClient
Private Shared ReadOnly client As New HttpClient()

Public Async Function UrlExistsAndIsAllowedAsync(url As String) As Task(Of Boolean)
  If Not Uri.TryCreate(url, UriKind.Absolute, Nothing) Then Return False
  Dim uri = New Uri(url)
  If uri.Scheme <> Uri.UriSchemeHttp AndAlso uri.Scheme <> Uri.UriSchemeHttps Then Return False

  Dim req = New HttpRequestMessage(HttpMethod.Head, uri)
  Dim res = Await client.SendAsync(req)
  If res.IsSuccessStatusCode Then
    Dim mt = If(res.Content.Headers.ContentType?.MediaType, "")
    If mt.StartsWith("image/") OrElse mt = "application/pdf" Then Return True
  End If

  ' fallback: small GET (range) to read headers/first bytes
  req = New HttpRequestMessage(HttpMethod.Get, uri)
  req.Headers.Range = New Headers.RangeHeaderValue(0, 0)
  res = Await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead)
  Return res.IsSuccessStatusCode AndAlso (res.Content.Headers.ContentType?.MediaType?.StartsWith("image/") OrElse res.Content.Headers.ContentType?.MediaType = "application/pdf")
End Function

Notes and cautions: performing network I/O inside a synchronous DataAnnotations.IsValid is not ideal (it will block threads). Prefer async server-side validation (controller-level, remote validation, or a background check) and set short timeouts. Servers sometimes misreport Content-Type; as a last resort check the file extension or examine magic bytes. Always sanitize/whitelist domains and schemes to reduce SSRF risk, and cache successful results to avoid repeated network calls.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.