如何创建自定义基本控制器?我的代码是对的?

时间:2017-08-03 04:06:44

标签: c# asp.net-mvc asp.net-core

public class BaseController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly IIdentityService _identityService;

    public BaseController(ApplicationDbContext context, IIdentityService identityService)
    {
        _context = context;
        _identityService = identityService;
    } 

    public BaseController()
    {
    }

     //reusable methods
     public async Task<Account> GetAccount()
     {
        //code to do something, i.e query database
     }


}
public class MyController : BaseController
{
    private readonly ApplicationDbContext _context;
    private readonly IIdentityService _identityService;

    public MyController(ApplicationDbContext context, IIdentityService identityService)
    {
        _context = context;
        _identityService = identityService;
    } 

    public async Task<IActionResult> DoSomething()
    {

      var account = await GetAccount(); 

      //do something

      Return Ok();
    }
}

2 个答案:

答案 0 :(得分:2)

@jonno发布的休息很好,但您需要修改MyController中的构造函数:

public class MyController : BaseController
{
    public MyController(ApplicationDbContext context, IIdentityService identityService)
         :base(conext, identityService)
    {
    } 

答案 1 :(得分:1)

您的基本控制器可以像删除其他公共呼叫一样,并将2个私有值转换为受保护。因为您正在从MyController扩展BaseController,所以您不需要重新启动值,只需调用它们即可。例如:

BaseController

public class BaseController : Controller
{
    protected readonly ApplicationDbContext _context;
    protected readonly IIdentityService _identityService;

    public BaseController(ApplicationDbContext context, IIdentityService identityService)
    {
        _context = context;
        _identityService = identityService;
    } 

     //reusable methods
     public async Task<Account> GetAccount()
     {
        //code to do something, i.e query database
     }


}

和你的MyController

public class MyController : BaseController
{
    public async Task<IActionResult> DoSomething()
    {

      var account = await GetAccount(); 

      //do something and you can call both _context and _identityService directly in any method in MyController

      Return Ok();
    }
}
相关问题