2017-05-11 64 views
1

我使用Owin.Testing作爲測試環境。在我的控制器中,我需要從調用者獲取遠程IP地址。使用Owin獲取遠程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; 
     } 

結果屬性不包含OwinContext的MS_HttpContext和RemoteIpAddress爲空。

是否有任何選項可以獲取IP?

回答

0

找到解決方案。爲此使用測試中間件。一切都在你的測試項目:

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