使用Owin.Testing时获取远程ip

时间:2017-05-11 07:21:13

标签: c# asp.net .net asp.net-web-api owin

我正在使用Owin.Testing作为测试环境。在我的控制器中,我需要从呼叫者那里获得远程IP地址。

//in my controller method
var ip = GetIp(Request);

的Util

private string GetIp(HttpRequestMessage request)
        {
            return request.Properties.ContainsKey("MS_HttpContext")
                       ? (request.Properties["MS_HttpContext"] as HttpContextWrapper)?.Request?.UserHostAddress
                       : request.GetOwinContext()?.Request?.RemoteIpAddress;
        }

因此,属性不包含MS_HttpContext,OwinContext的RemoteIpAddress为空。

是否有获取IP的选项?

1 个答案:

答案 0 :(得分:1)

找到解决方案。为此使用测试中间件。测试项目中的所有内容:

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>();