简体   繁体   中英

Injecting IHostingEnvironment into a Web API 2 controller

I am trying to inject an IHostingEnvironment into my Web API 2 controller like this:

public class ClaimsController : BaseApiController
{
    private IConfigurationRoot config;

    public ClaimsController(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        this.config = builder.Build();
    }
    //..other methods/actions
}

However, the compiler complains:

ExceptionMessage=An error occurred when trying to create a controller of type 'ClaimsController'. Make sure that the controller has a parameterless public constructor.

So I thought maybe I could use parameter injection but for the life of me I can't find any information on the world wide interweb to do this. Can anyone help?

It's a little bit old, but maybe someone use it... You can use ASP.NET core 2.0. There you don't have to even modify Startup.cs. You only need to inject it with constructor.

public class ClaimsController : Controller
{
    private IHostingEnvironment _env;

    public ClaimsController(IHostingEnvironment env)
    {
        _env = env;
    }
    //..other methods/actions
}

Be careful:

_env.WebRootPath

can be null if you haven't got directory wwwroot in your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM