无法解析 ValidateAntiforgeryToken 中间件的服务类型

Unable to resolve service type for ValidateAntiforgeryToken Middleware

我正在按照教程 here 为我的 Web 应用程序实施防伪令牌中间件,当我尝试 运行 我的 Swagger API 时遇到以下错误:

: 'Unable to resolve service for type 'Microsoft.AspNetCore.Antiforgery.IAntiforgery' while attempting to activate 'Middleware.ValidateAntiForgeryTokenMiddleware'.'

只需在 Startup.cs 中实现 Configure() 中的中间件就可以了,对吗(即 app.UseMiddlware<ValidateAntiForgeryTokenMiddleware>();)?

我想我不完全确定为什么它无法解析 IAntiforgery。这个需要在ConfigureServices()中设置吗?感谢在此问题上的任何帮助。

根据错误消息,我认为您可能没有在 startup.cs 文件中注入 IAntiforgery 服务。我建议你可以按照下面的代码添加它并解决问题。

   public void ConfigureServices(IServiceCollection services)
   {       
        services.AddAntiforgery();
   }