gpt4 book ai didi

c# - 将 IP 地址添加到 HttpRequestMessage

转载 作者:行者123 更新时间:2023-12-02 03:39:56 32 4
gpt4 key购买 nike

如何将 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"] 为 null,我无法执行测试。

下面的解决方案 - 请参阅我自己的答案。

最佳答案

感谢 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;

关于c# - 将 IP 地址添加到 HttpRequestMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15189350/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com