2013-03-03 136 views
3

如何將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」]爲空,我無法進行測試。

解決方案以下 - 請參閱我自己的答案。

回答

8

由於達文:首先,模擬System.Web.HttpContextBase並建立返回值Request.UserHostAddress,那麼,在您的測試設置,財產直接設置。

這裏是解決方案 -

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; 
+0

這是一個光榮的解決方案。 – Brad 2015-04-22 14:18:08

3

看來你正試圖從主機myserver獲取IP地址,在這種情況下,將不會被任何東西解決。這會使屬性MS_HttpContext爲空。

我會建議一種不同的方法。他建議

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; 
    } 
+0

感謝您的幫助。我也發佈了我自己的答案。 – tom 2013-03-04 02:32:47