1

I am creating an HTTP request and checking for a secure connection:

var httpRequest = new HttpRequest(null, "https://test.com", null);
bool IsSecureConnection = httpRequest.IsSecureConnection;

So why does this code return false?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mmohab
  • 2,303
  • 4
  • 27
  • 43
  • Take a look at http://stackoverflow.com/questions/998397/why-does-request-issecureconnection-return-false-when-true-is-expected. Might be relevant to your situation. – DWright Apr 14 '15 at 02:30
  • In general `HttpRequest` is not very mocking-friendly. So there is significant chance you need way more code to convince it to return values you want... If you need it for unit testing see if you can switch to MVC objects like `HttpRequestBase` which are friendlier - [virtual HttpRequestBase.IsSecure...](https://msdn.microsoft.com/en-us/library/system.web.httprequestbase.issecureconnection%28v=vs.110%29.aspx). – Alexei Levenkov Apr 14 '15 at 02:38

2 Answers2

1

If you are in a situation where you need to mock the HttpContext and by extension the HttpRequest for unit testing, then you can replace the HttpWorkerRequest object used internally to determine if a secure connection exists, as this object would normally not be set in this scenario.

    private static void FakeHttpContext(string url)
    {
        var uri = new Uri(url);
        var httpRequest = new HttpRequest(string.Empty, uri.ToString(), uri.Query.TrimStart('?'));
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);

        //Set the private _wr of httpRequest to a new SimpleWorkerRequest that always returns true
        if (url.StartsWith("https:"))
        {
            var type = httpRequest.GetType();

            var fi = type.GetField("_wr", BindingFlags.NonPublic | BindingFlags.Instance);
            fi.SetValue(httpRequest, new FakeWorkerRequest());
        }

        HttpContext.Current = httpContext;
    }

FakeWorkerRequest inherits from SimpleWorkerRequest class and simply returns true for IsSecure()

    public class FakeWorkerRequest: SimpleWorkerRequest
    {
        public FakeWorkerRequest(): base("","","","",null)
        {

        }

        public override bool IsSecure()
        {
            return true;
        }
    }

Calls to HttpContext.Current.Request.IsSecureConnection() should now return true

James Westgate
  • 11,306
  • 8
  • 61
  • 68
0

According to source code for HttpRequestBase.IsSecureConnection it always returns false when using that public constructor.

If you need for unit testing consider either refactoring your code to depend on your custom interface which you can mock or if possible switch to MVC's HttpRequestBase.

As a hack you can try reflection and call internal constructor...

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179