【发布时间】:2014-06-11 12:37:36
【问题描述】:
我的场景:我的应用程序是一个 Web Api 2 应用程序,它使用业务逻辑和存储库层进行数据访问。 Web 应用程序使用 ASP.NET Impersonation 作为访问网站的用户登录到数据库(通过 PKI 进行身份验证)。我有几个异步控制器方法。但是,当我在数据访问方法上await 时,数据库调用可能会在不同的线程上完成,然后该线程将以我的应用程序池的身份访问数据库,该应用程序池不允许连接到数据库。
示例控制器:
public class TestApiController : ApiController {
private IBusinessLogicObject _myBlObject;
public TestApiController(IBusinessLogicObject myBlObject){
_myBlObject = myBlObject; //Populated through Unity
}
public async Task<int> CountMyJobs(string name){
return await _myBlObject.CountMyJobsAsync(name);
}
}
示例业务逻辑类:
public class BusinessLogicObject : IBusinessLogicObject
{
private IGenericRepository<Job> _jobRepository;
public BusinessLogicObject(IGenericRepository<Job> _jobRepository)
{
_jobRepository = jobRepository; //Populated with Unity
}
public Task<int> CountMyJobsAsync(string name)
{
using (WindowsIdentity.GetCurrent().Impersonate())
{
//JobRepository is effectively a DbSet<Job> and this call returns IQueryable<Job>
return _jobRepository.Where(i => i.Name == name).CountAsync();
}
}
}
如果我将 using 语句移动到控制器中(包裹在 await 周围),它可以正常工作。
问题似乎是因为await 在模拟上下文之外,它不会模拟数据库调用(CountAsync())并且我无法打开与我的数据库的连接。
问题:
有没有办法可以在我的控制器方法上编写ActionFilter 或其他属性,以便方法本身(包含等待调用)将自动包装在 using 语句中?
【问题讨论】:
标签: c# async-await asp.net-web-api impersonation action-filter