中间件只实例化一次,因此它是一个有效的单例.
因此,您注入到Middlewares构造函数中的所有内容都将从单例容器(您可以通过app.ApplicationServices
Configure方法内部访问的容器)中解析出来.
我看到你IAccountService
被注入中间件,所以这似乎导致了这个问题.您必须使用在Invoke方法中基于每个上下文解析它
public Task Invoke(HttpContext context, IAccountService accountService) { // If the request path doesn't match, skip if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal)) { return _next(context); } if (!context.Request.Method.Equals("POST") || !context.Request.ContentType.Contains("application/json")) { context.Response.StatusCode = 400; return context.Response.WriteAsync("Bad request."); } return GenerateToken(context, accountService); }
要么
public Task Invoke(HttpContext context) { var accountService = context.RequestServices.GetRequiredService(); // If the request path doesn't match, skip if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal)) { return _next(context); } if (!context.Request.Method.Equals("POST") || !context.Request.ContentType.Contains("application/json")) { context.Response.StatusCode = 400; return context.Response.WriteAsync("Bad request."); } return GenerateToken(context, accountService); }