6

如何将 IP 地址添加到 HttpRequestMessage?

我正在为 Web.API 应用程序编写单元测试,我有一个 AuthorizeAttribute 来检查调用者的 IP 地址 -

        string[] AllowedIPs = new string[] { "127.0.0.1",  "::1" }
        string sourceIP = "";

        var contextBase = actionContext.Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;

        if (contextBase != null)
        {
            sourceIP = contextBase.Request.UserHostAddress;
        }

        if (!string.IsNullOrEmpty(sourceIP))
        {
            return AllowedIPs.Any(a => a == sourceIP);
        }
        return false;

我构建一个测试请求如下 -

    var request = CreateRequest("http://myserver/api/CustomerController, "application/json", HttpMethod.Get);            
    HttpResponseMessage response = client.SendAsync(request).Result;

. .

    private HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
    {
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri(url);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
        request.Method = method;
        return request;
    } 

但是 actionContext.Request.Properties["MS_HttpContext"] 为空,我无法执行测试。

下面的解决方案- 请参阅我自己的答案。

4

2 回答 2

12

感谢 Davin 的建议。

这是解决方案 -

private HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
{
    var request = new HttpRequestMessage();

    var baseRequest = new Mock<HttpRequestBase>(MockBehavior.Strict);
    var baseContext = new Mock<HttpContextBase>(MockBehavior.Strict);

    baseRequest.Setup(br => br.UserHostAddress).Returns("127.0.0.1");
    baseContext.Setup(bc => bc.Request).Returns(baseRequest.Object);


    request.RequestUri = new Uri(url);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));

    request.Properties.Add("MS_HttpContext", baseContext.Object);

    request.Method = method;
    return request;
} 

然后按以下方式使用该方法 -

 var request = CreateRequest("http://myserver/api/CustomerController, "application/json", HttpMethod.Get);            
 HttpResponseMessage response = client.SendAsync(request).Result;
于 2013-03-04T02:01:57.813 回答
4

您似乎正在尝试从主机获取 IP 地址myserver,在这种情况下,任何东西都无法解析。这使属性为MS_HttpContext空。

我会建议一种不同的方法。首先,模拟System.Web.HttpContextBase并设置返回值Request.UserHostAddress,然后,在您的测试设置中,直接设置属性:

private HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
    {
        var request = new HttpRequestMessage();
        request.RequestUri = new Uri(url);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
        request.Method = method;
        request.Property["MS_HttpContext"] = mockedHttpContextBase //here
        return request;
    } 
于 2013-03-03T22:39:51.807 回答