使用Owin时获取远程IP [英] Get remote ip while using Owin.Testing

查看:52
本文介绍了使用Owin时获取远程IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用

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为空.

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

是否有获取IP的选项?

Is there any option to get IP?

推荐答案

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

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

处理程序:

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创建测试服务器:

And then create test server via TestStartup:

TestServer = TestServer.Create<TestStartup>();

这篇关于使用Owin时获取远程IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆