1

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?

PCG
  • 2,049
  • 5
  • 24
  • 42

1 Answers1

4

You might want to send a HEAD request. Quoting 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.

As for the implementation, maybe check out this post, example snippet by AlexandreJBRodrigues:

HttpClient httpClient = new HttpClient();

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

HttpResponseMessage response = 
   await httpClient.SendAsync(request);
Yom T.
  • 8,760
  • 2
  • 32
  • 49