Skip to content

Instantly share code, notes, and snippets.

@keithbloom
Created October 27, 2011 20:44
Show Gist options
  • Save keithbloom/1320809 to your computer and use it in GitHub Desktop.
Save keithbloom/1320809 to your computer and use it in GitHub Desktop.
MefToExtendAHttpModule
public interface ISetCookies
{
void SetCookie(HttpContext context);
}
[Import]
public IEnumerable<ISetCookies> CookieSetters { get; set; }
public void Init(HttpApplication context)
{
// Setup the MEF container
var catalog = DirectoryCatalog(context.Request.PhysicalApplicationPath + "\\bin");
var container = new CompositionContainer(catalog);
var batch = new CompositionBatch();
batch.AddPart(this);
container.Compose(batch);
// Setup events
context.PostAuthenticateRequest += new EventHandler(Context_PostAuthenticateRequest);
context.PostAuthorizeRequest += new EventHandler(Context_PostAuthorizeRequest);
}
void Context_PostAuthorizeRequest(object sender, EventArgs e)
{
var context = ((HttpApplication) sender).Context;
if (context != null)
{
foreach (var setter in CookieSetters)
{
setter.SetCookie(context);
}
}
}
namespace Keith.SimpleCookie
{
[Export(typeof(ISetCookies))]
public class SimpleCookie : ISetCookies
{
public void SetCookie(HttpContext context)
{
context.Response.Cookies.Add(new HttpCookie("Name", context.User.Identity.Name));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment