如何为HttpRequestMessage添加IP地址?
我正在为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”]为空,我无法执行测试。
以下解决方案 - 请参阅我自己的答案。
答案 0 :(得分:8)
感谢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;
答案 1 :(得分:3)
您似乎正在尝试从主机myserver
获取IP地址,在这种情况下,任何内容都无法解析。这使属性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;
}