如何将 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"] 为空,我无法执行测试。
下面的解决方案- 请参阅我自己的答案。