C# 使用Owin.Testing时获取远程ip
我使用Owin.Testing作为测试环境。在我的控制器中,我需要从调用方获取远程ip地址C# 使用Owin.Testing时获取远程ip,c#,asp.net,.net,asp.net-web-api,owin,C#,Asp.net,.net,Asp.net Web Api,Owin,我使用Owin.Testing作为测试环境。在我的控制器中,我需要从调用方获取远程ip地址 //in my controller method var ip = GetIp(Request); 利用率 因此,属性不包含MS_HttpContext,并且OwinContext的RemoteIpAddress为空 是否有获取IP的选项?找到了解决方案。为此使用测试中间件。测试项目中的所有内容: public class IpMiddleware : OwinMiddleware { pri
//in my controller method
var ip = GetIp(Request);
利用率
因此,属性不包含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;
}
}
然后通过TestStartup创建测试服务器:
TestServer = TestServer.Create<TestStartup>();
TestServer=TestServer.Create();
public class TestStartup : Startup
{
public new void Configuration(IAppBuilder app)
{
app.UseIpMiddleware(new IpOptions {RemoteIp = "127.0.0.1"});
base.Configuration(app);
}
}
TestServer = TestServer.Create<TestStartup>();