如何將IP地址添加到HttpRequestMessage?將IP地址添加到HttpRequestMessage
我寫單元測試用於Web.API應用,我有檢查呼叫者的IP地址的AuthorizeAttribute -
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;
}
BUT actionContext.Request.Properties [ 「MS_HttpContext」]爲空,我無法進行測試。
解決方案以下 - 請參閱我自己的答案。
這是一個光榮的解決方案。 – Brad 2015-04-22 14:18:08