Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access IHostingEnvironment in middleware class

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);

    }
}
like image 283
RonC Avatar asked Dec 12 '16 19:12

RonC


People also ask

How do I get IWebHostEnvironment in ConfigureServices?

You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices. public Startup(IWebHostEnvironment env, IApplicationEnvironment appEnv) { ... your code here...

How do I get WebRootPath in .NET Core?

ContentRootPath – Path of the root folder which contains all the Application files. You will need to import the following namespace. In the below example, the IHostingEnvironment is injected in the Controller and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.

How do I add middleware to the application request pipeline?

Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below. We can add middleware using app. UseMiddleware<MyMiddleware>() method of IApplicationBuilder also. Thus, we can add custom middleware in the ASP.NET Core application.

How do you check if current environment is development or not?

How do you check if current environment is development or not? If you need to check whether the application is running in a particular environment, use env. IsEnvironment("environmentname") since it will correctly ignore case (instead of checking if env. EnvironmentName == "Development" for example).


1 Answers

method injection works, just add it to the method signature

 public async Task Invoke(HttpContext context, IHostingEnvironment env) {...}
like image 127
Joe Audette Avatar answered Oct 13 '22 22:10

Joe Audette