一种方法是创建使用类继承,但是有没有其他方法可以重用我在另一个控制器中的一个控制器中创建的方法?ASP.NET核心 - 如何重用在另一个控制器中的一个控制器中创建的方法?
编辑:我应该使用这样的自定义基础控制器吗?
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();
}
}
你不想这样做。 – CSharper
这可能会有帮助。 https://softwareengineering.stackexchange.com/questions/264392/is-a-good-practice-to-call-a-controller-function-from-another-controller。如果你仍然坚持,那么更干净的方法是使用“RedirectToAction”。 –