Search code examples
c#.netdependency-injectionmiddleware

Only apply https redirection middleware based on a scoped service


I have a web application that runs multiple websites. Based on a configuration loaded from the database, some sites must be redirected to HTTPS and some not. I would like to make use of the default HTTPSRedirection middleware, so have included it in my startup config as follows :

app.UseWhen(httpContext =>
{
    return app.Services.GetService<IContext>()!.IsForceHttps;
}, httpApp =>
{
    httpApp.UseHttpsRedirection();
});

The issue I am having now is that IContext is a scoped service and cannot be referenced at this point ( from the root context ).

I considered extending the HttpsRedirectionMiddleware class and then injecting IContext into the Invoke method, but then I got "multiple Invoke instances found" error on container startup.

So apart from basically rewriting the default HttpsRedirectionMiddleware ( don't want to do that ) is there any other way to achieve this?

P.S.: I would like to re-use this type of solution in other areas as well ( i.e. to activate the mini-profiler or to forward headers or to set SameOrigin etc.. )

Remember, this values will all be request/session specific


Solution

  • Just thought I would post my solution here for any future reference. The trick was to resolve the scoped dependency using the provided httpContext ( as it is in essence scoped itself )

    app.UseWhen(httpContext =>
    {
        try
        {
            var context = httpContext.RequestServices.GetService<IContext>();
            return context!.ForceHttps;
        }
        catch (Exception ex)
        {
            Log.Error(ex, "Failed to resolve logic for HTTPS redirection, defaulting to true");
            return true;
        }
                
    
     }, httpApp => { httpApp.UseHttpsRedirection(); });