带有自定义基础控制器的控制器不工作
Controller with custom base controller not working
更新
试图澄清我的问题
我有一个 ASP.NET 5 Web Api 应用程序。我正在尝试创建一个使用自定义基础控制器的控制器 class。只要我向基本控制器添加构造函数,MVC 就无法再找到 Generic
class.
中定义的 Get()
端点
这个有效:
当我导航到 /api/person
时,Get()
端点被触发,定义在 Generic
class
通用:
public class Generic
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
个人控制器
[Route("api/[controller]")]
public class PersonController : Generic
{
}
这不行
当我导航到 /api/person
时,Get()
终点是 而不是 触发的。唯一添加的是 Generic
class 和 PersonController
class.
中的构造函数
public class Generic
{
protected DbContext Context { get; set; }
public Generic(DbContext context)
{
Context = context;
}
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
个人控制器
[Route("api/[controller]")]
public class PersonController : Generic
{
public PersonController(DbContext context) : base(context) { }
}
这是一个错误还是我做错了什么?
您的问题与从另一个基础继承无关class。我认为问题是,您的 DbContext
的正确实现没有被注入到构造函数中。由于 asp.net 5 是如此 modular/dependency 可注入,您需要明确配置它。
在您的 Startup.cs class 的 ConfigureServices
方法中,注册您的 DbContext
服务,以便 MVC 将使用它并将其注入到您的 class 控制器需要的时候。
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddDbContext<DbContext>();
services.AddMvc();
}
更新
试图澄清我的问题
我有一个 ASP.NET 5 Web Api 应用程序。我正在尝试创建一个使用自定义基础控制器的控制器 class。只要我向基本控制器添加构造函数,MVC 就无法再找到 Generic
class.
Get()
端点
这个有效:
当我导航到 /api/person
时,Get()
端点被触发,定义在 Generic
class
通用:
public class Generic
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
个人控制器
[Route("api/[controller]")]
public class PersonController : Generic
{
}
这不行
当我导航到 /api/person
时,Get()
终点是 而不是 触发的。唯一添加的是 Generic
class 和 PersonController
class.
public class Generic
{
protected DbContext Context { get; set; }
public Generic(DbContext context)
{
Context = context;
}
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
个人控制器
[Route("api/[controller]")]
public class PersonController : Generic
{
public PersonController(DbContext context) : base(context) { }
}
这是一个错误还是我做错了什么?
您的问题与从另一个基础继承无关class。我认为问题是,您的 DbContext
的正确实现没有被注入到构造函数中。由于 asp.net 5 是如此 modular/dependency 可注入,您需要明确配置它。
在您的 Startup.cs class 的 ConfigureServices
方法中,注册您的 DbContext
服务,以便 MVC 将使用它并将其注入到您的 class 控制器需要的时候。
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddDbContext<DbContext>();
services.AddMvc();
}