2

I want X-Frame-Options using c#. For this I am creating like the following.

  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(System.Uri.UnescapeDataString(url));
            string frameSupport = string.Empty;
            using (WebResponse webResponse = request.GetResponse())
                frameSupport = webResponse.Headers["X-Frame-Options"];

But when I pass url without http or https, I am getting the following issue.

Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.HttpWebRequest'.
9
  • 1
    I think the solution is obvious. Pass the proper scheme. How is WebRequest supposed whether it's a file, ftp, http or https request? Why are you using an invalid URL in the first place? Commented Mar 22, 2017 at 11:59
  • Furthermore, there is no HttpWebRequest.Create method. This is a factory method defined on WebRequest. The compiler generates a warning and Visual Studio adds squigglies when you try to call a base static method like this Commented Mar 22, 2017 at 12:02
  • Sometime user may enter url like "//google.com" without http or https. So the url will be redirect to the appropriate http or https. So for this we allowed the user to give input like this. Can we get web request using "//google.com" Commented Mar 22, 2017 at 12:02
  • 3
    Seriously - use a proper URL. Why do you expect such invalid URLs to work at all? They don't. Browsers attempt to guess and actually try to hit multiple ULRs with various prefixes when you type incomplete addresses. Commented Mar 22, 2017 at 12:04
  • 2
    If the request doesn't work, you can try https:. Commented Mar 22, 2017 at 12:30

1 Answer 1

2

If you use HttpWebRequest.Create, you are actually calling WebRequest.Create (since HttpWebRequest extends WebRequest).
Therefore, the method is not only for http requests, but it tries to get the actual type of the request based on the uri scheme.
If you omit http(s) scheme, it can't know what type of request you are performing, so, in this case, it assumes it is a FileWebRequest

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.