【发布时间】:2017-02-08 16:49:54
【问题描述】:
我正在尝试将 IHostingEnvironment 注入我的 Web API 2 控制器,如下所示:
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
}
但是,编译器抱怨:
ExceptionMessage=An error occurred when trying to create a controller of type 'ClaimsController'. Make sure that the controller has a parameterless public constructor.
所以我想也许我可以使用参数注入,但在我的一生中,我在全球互联网上找不到任何信息来做到这一点。有人可以帮忙吗?
【问题讨论】:
-
显示你的
Startup.cs -
没有这些
-
什么版本的web api?标签说 web api 2 但
IHostingEnvironment来自 Asp.net 核心。IConfigurationRoot应该在 Startup 中而不是直接在控制器中。 -
是的,我使用的是 Web API 2,但从核心导入了各种位。这是错误的做法吗?
标签: c# .net visual-studio-2015 dependency-injection asp.net-web-api2