2

So I had this problem where I absolutely needed to use the IoC of the solution I was working (and Am working) on but also needed to use an HttpModule to redirect the request before it even got in the container.

Well I found some ways to do it that weren't what I needed nor wanted. I didn't want to add a dependency to a library to use it on just an HttpModule.

Well after fiddling a little with the module I got to a success. It may not be pretty, it may cause some eye soreness, but it's working!

It will only actually use the EndRequest once and a simple boolean comparison isn't that costly. Also if for some reason the service isn't resolved propperly, it will use the EndRequest again. "Simple"!

I hope to have helped all the others that had the same problem as me!

public sealed class ChannelRedirectionModule : IHttpModule
{
    private readonly Func<IChannelRedirectionService> _channelRedirectionService;
    private static bool _firstCall = true;

    public ChannelRedirectionModule()
    {
        _channelRedirectionService = DependencyResolver.Current.GetService<Func<IChannelRedirectionService>>();
    }


    public void Init(HttpApplication context)
    {
        context.BeginRequest += (sender, e) =>
        {
            if (!_firstCall)
            {
                Redirect(sender, e);
            }
        };
        context.EndRequest += (sender, e) =>
        {
            if (_firstCall)
            {
                Redirect(sender, e);
            }
        };
    }

    private void Redirect(object sender, EventArgs e)
    {
        var app = (sender as HttpApplication);
        var channelRedirectionService = _channelRedirectionService();
        if (channelRedirectionService == null)
        {
            _firstCall = true;
            return;
        }
        _firstCall = false;
        string redirectUrl = channelRedirectionService.GetRedirectAddressForChannelId(app.Request);
        if (!string.IsNullOrEmpty(redirectUrl))
        {
            app.Response.Redirect(redirectUrl);
        }
    }

    public void Dispose()
    {
        //there's realy nothing to be disposed here, 
        //but we're enforced to have this by the IHttpModule interface...
    }
}
Bandjalah
  • 21
  • 2
  • 1
    1) Please post your answer as an answer (you are allowed to answer your own question). 2) Using a static boolean variable as a flag means you redirect the first request of the *first user only* after the app pool recycles. 3) It would be far better (and easier) to put this logic into an MVC [global action filter](https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx) rather than an HTTP Module. If you need to use DI in your filter, you just need to use a [filter provider](http://stackoverflow.com/a/36224308/181087) to inject its dependencies through the constructor. – NightOwl888 Jul 01 '16 at 21:32

0 Answers0