在HttpRequestMessage中添加IP地址
本文关键字:IP 地址 添加 HttpRequestMessage | 更新日期: 2023-09-27 18:01:53
如何添加一个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。属性["MS_HttpContext"]为空,我无法执行测试。
解决方案如下 -查看我自己的答案
感谢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;
似乎您正试图从主机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;
}