Skip to content

Instantly share code, notes, and snippets.

@chaoaretasty
Created October 14, 2013 16:53
Show Gist options
  • Save chaoaretasty/6978640 to your computer and use it in GitHub Desktop.
Save chaoaretasty/6978640 to your computer and use it in GitHub Desktop.
Hackily enable HttpContext in WebAPI and Autofac
/*
While generally using HttpContext, and all of the related properties such as
Cookies and Session, in WebAPI is not the right way sometimes it needs to be
done, especially when migrating existing code before doing a full rewrite but
could happen in any legacy MVC project you want to bring WebAPI into.
When using Autofac there is the AutofacWebTypesModule which allows you to resolve
these dependencies, all of which come from resolving HttpContextBase.
WebAPI doesn't provide HttpContext directly but if hosted in IIS rather than
self host it is accessible via
HttpRequestMessage.Properties["MS_HttpContext"]
This replaces Autofac's registration for HttpContextBase with one that falls
back to WebAPI's HttpContext
*/
builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration);
builder.Register(c =>
HttpContext.Current != null ?
new HttpContextWrapper(HttpContext.Current) :
c.Resolve<System.Net.Http.HttpRequestMessage>().Properties["MS_HttpContext"])
.As<HttpContextBase>()
.InstancePerHttpRequest();
@chaoaretasty
Copy link
Author

Glad to see old hacks like this still finding a use

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