asp.net-coremiddlewareswagger-uiantiforgerytoken

Unable to resolve service type for ValidateAntiforgeryToken Middleware


I'm following the tutorial here for implementing Antiforgery token middleware for my web application and I'm getting the following error when I try to run my Swagger API:

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

Just implementing the middleware in Configure() in Startup.cs should work, correct (i.e. app.UseMiddlware<ValidateAntiForgeryTokenMiddleware>();)?

I guess I'm not entirely sure why it's unable to resolve IAntiforgery. Does this need to be set up in ConfigureServices()? I appreciate any help on this issue.


Solution

  • According to the error message, I think you may not inject the IAntiforgery service inside your startup.cs file. I suggest you could follow below codes to add it and solve the issue.

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