Created
October 14, 2013 16:53
-
-
Save chaoaretasty/6978640 to your computer and use it in GitHub Desktop.
Hackily enable HttpContext in WebAPI and Autofac
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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(); |
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
Great hack! Thanks for taking the time to post. Hugely useful for projects where utilizing legacy code.