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?
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?
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
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...