Dis*_*ile 4 c# async-await asp.net-web-api asp.net-web-api2
ApiController 是否有可用于初始化异步资源的扩展点/覆盖?
我想要这样的东西:
public ValuesController : ApiController
{
private IFoo _foo;
protected async override void InitializeAsync(HttpControllerContext controllerContext)
{
_foo = await CreateFooAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以在每个控制器动作中做到这一点,但我想避免必须在 4/5 不同的动作中做到这一点。
您可以覆盖核心控制器方法:ExecuteAsync. 像这样:
public override async Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) {
_foo = await CreateFooAsync();
return await base.ExecuteAsync(controllerContext, cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)