Get remote ip while using Owin.Testing

五迷三道 提交于 2019-12-08 03:15:26

问题


I'm using Owin.Testing as test env. In my controller i need to get remote ip address from the caller.

//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;
        }

As a result Properties does not contains MS_HttpContext and RemoteIpAddress of OwinContext is null.

Is there any option to get IP?


回答1:


Found the solution. Use testing middleware for this. Everything in your tests project:

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

Handler:

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

Testing startup:

public class TestStartup : Startup
{
    public new void Configuration(IAppBuilder app)
    {
        app.UseIpMiddleware(new IpOptions {RemoteIp = "127.0.0.1"});
        base.Configuration(app);          
    }
}

And then create test server via TestStartup:

TestServer = TestServer.Create<TestStartup>();


来源:https://stackoverflow.com/questions/43908966/get-remote-ip-while-using-owin-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!