Skip to content

Instantly share code, notes, and snippets.

@stephenpope
Created March 4, 2015 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenpope/1a59dfa94794146caad6 to your computer and use it in GitHub Desktop.
Save stephenpope/1a59dfa94794146caad6 to your computer and use it in GitHub Desktop.
Getting a vNext HttpContext feature using Nancy
using Nancy;
using Nancy.Owin;
public class HomeModule : NancyModule
{
public HomeModule()
{
Get["/{id?}"] = _ =>
{
var owin = this.Context.GetOwinEnvironment();
var http = (HttpContext)owin[typeof(HttpContext).FullName];
var myFeature = http.GetFeature<MyFeature>();
return myFeature.DoSomething();
};
}
}
@khellang
Copy link

khellang commented Mar 4, 2015

Nice! 😁

You could wrap that in an extension method

public static class AspNetExtensions
{
    public static T GetFeature<T>(this NancyContext context)
    {
        var httpContext = context.GetHttpContext();
        if (httpContext != null)
        {
            return httpContext.GetFeature<T>();
        }

        return null;
    }

    public static HttpContext GetHttpContext(this NancyContext context)
    {
        var owinEnvironment = context.GetOwinEnvironment();

        var httpContextKey = typeof(HttpContext).FullName;

        object httpContextObject;
        if (owinEnvironment.TryGetValue(httpContextKey , out httpContextObject))
        {
            return httpContextObject as HttpContext;
        }

        return null;
    }
}

So your module becomes

public class HomeModule : NancyModule
{
    public HomeModule()
    {
        Get["/{id?}"] = _ => this.Context.GetFeature<MyFeature>().DoSomething();
    }
}

✨👯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment