所以我正在测试一些中间件并找到导致我的问题的原因。这是一个非常简单的解释。
例如我有这个
public class AuthMiddleware
{
private HttpClient _client;
//have constructor as standard so removed to keep example short as not important
public async Task Invoke(IHttpClientFactory clientFactory)
{
_client = GetClientAsync();
await _next.Invoke(context);
}
private async Task<HttpClient> GetClientAsync(IHttpClientFactory clientFactory)
{
//NOTE: I would expect the _client to be null on every call to this method
//However once it is created it does not get created again.
if(_client == null)
{
_client = clientFactory.CreateClient("TestClient");
}
return _client;
}
}
至于我的注释 _client
是实例变量而不是静态的,那么为什么它会在每个请求上保存一个实例而不是 null 并按预期重新创建?
最佳答案
(基于约定)ASP.NET Core 中的中间件仅在启动时创建:
Middleware is constructed once per application lifetime.
因此,为所有请求保留实例字段。
如果您需要对中间件的范围进行更多控制,可以使用 Factory-based middleware
关于c# - 在中间件中为什么这个值只设置一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67913104/