2017-05-11 4 views
1

Ich benutze Owin.Testing als Test env. In meinem Controller muss ich Remote-IP-Adresse vom Anrufer erhalten.Erhalten Sie Remote-IP bei der Verwendung von Owin.Testing

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

Als Ergebnis Eigenschaften nicht enthält MS_HttpContext und RemoteIP von OwinContext null ist.

Gibt es eine Option, um IP zu bekommen?

Antwort

0

Die Lösung gefunden. Verwenden Sie hierfür eine Test-Middleware. Alles in Ihren Tests Projekt:

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 Inbetriebnahme:

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

Und dann Testserver über TestStartup erstellen:

TestServer = TestServer.Create<TestStartup>(); 
Verwandte Themen