使用 Owin.Testing 时获取远程 ip
Get remote ip while using Owin.Testing
我正在使用 Owin.Testing 作为测试环境。在我的控制器中,我需要从调用者那里获取远程 IP 地址。
//in my controller method
var ip = GetIp(Request);
实用程序
private string GetIp(HttpRequestMessage request)
{
return request.Properties.ContainsKey("MS_HttpContext")
? (request.Properties["MS_HttpContext"] as HttpContextWrapper)?.Request?.UserHostAddress
: request.GetOwinContext()?.Request?.RemoteIpAddress;
}
因此 Properties 不包含 MS_HttpContext 并且 OwinContext 的 RemoteIpAddress 为空。
有获取IP的选项吗?
找到解决方案。为此使用测试中间件。测试项目中的所有内容:
public class IpMiddleware : OwinMiddleware
{
private readonly IpOptions _options;
public IpMiddleware(OwinMiddleware next, IpOptions options) : base(next)
{
this._options = options;
this.Next = next;
}
public override async Task Invoke(IOwinContext context)
{
context.Request.RemoteIpAddress = _options.RemoteIp;
await this.Next.Invoke(context);
}
}
处理程序:
public sealed class IpOptions
{
public string RemoteIp { get; set; }
}
public static class IpMiddlewareHandler
{
public static IAppBuilder UseIpMiddleware(this IAppBuilder app, IpOptions options)
{
app.Use<IpMiddleware>(options);
return app;
}
}
测试启动:
public class TestStartup : Startup
{
public new void Configuration(IAppBuilder app)
{
app.UseIpMiddleware(new IpOptions {RemoteIp = "127.0.0.1"});
base.Configuration(app);
}
}
然后通过 TestStartup 创建测试服务器:
TestServer = TestServer.Create<TestStartup>();
我正在使用 Owin.Testing 作为测试环境。在我的控制器中,我需要从调用者那里获取远程 IP 地址。
//in my controller method
var ip = GetIp(Request);
实用程序
private string GetIp(HttpRequestMessage request)
{
return request.Properties.ContainsKey("MS_HttpContext")
? (request.Properties["MS_HttpContext"] as HttpContextWrapper)?.Request?.UserHostAddress
: request.GetOwinContext()?.Request?.RemoteIpAddress;
}
因此 Properties 不包含 MS_HttpContext 并且 OwinContext 的 RemoteIpAddress 为空。
有获取IP的选项吗?
找到解决方案。为此使用测试中间件。测试项目中的所有内容:
public class IpMiddleware : OwinMiddleware
{
private readonly IpOptions _options;
public IpMiddleware(OwinMiddleware next, IpOptions options) : base(next)
{
this._options = options;
this.Next = next;
}
public override async Task Invoke(IOwinContext context)
{
context.Request.RemoteIpAddress = _options.RemoteIp;
await this.Next.Invoke(context);
}
}
处理程序:
public sealed class IpOptions
{
public string RemoteIp { get; set; }
}
public static class IpMiddlewareHandler
{
public static IAppBuilder UseIpMiddleware(this IAppBuilder app, IpOptions options)
{
app.Use<IpMiddleware>(options);
return app;
}
}
测试启动:
public class TestStartup : Startup
{
public new void Configuration(IAppBuilder app)
{
app.UseIpMiddleware(new IpOptions {RemoteIp = "127.0.0.1"});
base.Configuration(app);
}
}
然后通过 TestStartup 创建测试服务器:
TestServer = TestServer.Create<TestStartup>();