对于HTTPS URL,HttpRequest.IsSecureConnection返回false

时间:2015-04-14 02:20:01

标签: c# httprequest

我正在创建HTTP请求并检查安全连接:

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

那么为什么这段代码会返回false?

2 个答案:

答案 0 :(得分:0)

根据HttpRequestBase.IsSecureConnection的源代码,在使用该公共构造函数时,它始终返回false

如果您需要进行单元测试,请考虑重构您的代码以依赖您可以模拟的自定义界面,或者如果可能,请切换到MVC' HttpRequestBase

作为一个hack,你可以尝试反射并调用内部构造函数......

答案 1 :(得分:0)

如果您需要模拟HttpContext并通过扩展HttpRequest进行单元测试,则可以替换内部使用的HttpWorkerRequest对象来确定是否存在安全连接,因为在这种情况下通常不会设置该对象。

    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继承自SimpleWorkerRequest类,并仅对IsSecure()返回true。

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

        }

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

HttpContext.Current.Request.IsSecureConnection()的呼叫现在应该返回true