我可以直接基地到BaseController在MVC?



我有这样的代码:

public class ProductController : Controller
{
private readonly IOrderedProductService _orderedProductService;
public ProductController(ApplicationDbContext dbContext, IOrderedProductService orderedProductService)
: base(dbContext)
{
_orderedProductService = orderedProductService;
}
}

. NET MVC项目,其中base(dbContect)应该是BaseController.BaseController(ApplicationDbContext dbContect),但它已经变成了Controller.Controller()

我该如何修复它?

你的类ProductController继承自Controller-它的基础是Controller

base(dbContect)的引用正确指向Controller.Controller()

为了使base(dbContect)调用BaseController.BaseController(ApplicationDbContext dbContect),您需要将类定义更改为:

public class ProductController : BaseController
{
private readonly IOrderedProductService _orderedProductService;
public ProductController(ApplicationDbContext dbContext, IOrderedProductService orderedProductService)
: base(dbContext)
{
_orderedProductService = orderedProductService;
}
}

这将把ProductController的基类更改为BaseController,并且对基构造函数的调用将如您所愿。

你应该创建一个新的类名BaseController:

public class BaseController : Controller {
private readonly DbContext dbContext;
public BaseController(DbContext dbContext) {
this.dbContext = dbContext;
}
}

那么你应该继承你的ProductController,像

public class ProductController : BaseController {
public ProductController(DbContext dbContext) : base(dbContext){
} 
}

最新更新