【发布时间】:2018-01-10 10:34:06
【问题描述】:
一种方法是创建使用类继承,但有没有其他方法可以重用我在一个控制器中创建的方法在另一个控制器中?
编辑:我应该使用这样的自定义基本控制器吗?
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();
}
}
【问题讨论】:
-
你不想这样做。
-
这可能会有所帮助。 softwareengineering.stackexchange.com/questions/264392/…。如果您仍然坚持,那么更清洁的方法 imo 是使用“RedirectToAction”。
标签: c# class inheritance asp.net-core