How to access IHostingEnvironment in middleware class
Asked Answered
T

2

12

In Asp.Net Core if a custom piece of middleware is created and placed in it's own class how does one get access to IHostingEnvironment from inside the middleware?

For example in my class below I thought I could inject IHostingEnvironment into the contstructor but it's always null. Any other ideas on how to get access to IHostingEnvironment?

public class ForceHttps {
    private readonly RequestDelegate _next;
    private readonly IHostingEnvironment _env;

    /// <summary>
    /// This approach to getting access to IHostingEnvironment 
    /// doesn't work.  It's always null
    /// </summary>
    /// <param name="next"></param>
    /// <param name="env"></param>
    public ForceHttps(RequestDelegate next, IHostingEnvironment env) {
        _next = next;
    }


    public async Task Invoke(HttpContext context) {
        string sslPort = "";
        HttpRequest request = context.Request;


        if(_env.IsDevelopment()) {
            sslPort = ":44376";
        }

        if(request.IsHttps == false) {
            context.Response.Redirect("https://" + request.Host + sslPort + request.Path);
        }

        await _next.Invoke(context);

    }
}
Thermoluminescent answered 12/12, 2016 at 19:26 Comment(1)
My bad, injecting into the constructor does work, I just forgot to assign the constructor parameter to the member var _env. So later in the Invoke method, _env is null. Hand against forehead! It's great to learn that I can inject it into the Invoke method though.Thermoluminescent
A
23

method injection works, just add it to the method signature

 public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}
Antheridium answered 12/12, 2016 at 19:31 Comment(0)
N
2

Now days, on modern .NET version, the solution might look like:

public CustomMiddleware(RequestDelegate next, IWebHostEnvironment env) {...}

The new IWebHostEnvironment have to be passed into middleware constructor instead of deprecated IHostingEnvironment.

Nga answered 22/2, 2023 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.