{"record":{"id":"8e41e0757ea4b6a4","repo":"dotnet/aspnetcore","slug":"unable-to-find-the-required-services-please-add-a","errorCode":null,"errorMessage":"Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAntiforgery' in the application startup code.","messagePattern":"Unable to find the required services\\. Please add all the required services by calling 'IServiceCollection\\.AddAntiforgery' in the application startup code\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs","lineNumber":54,"sourceCode":"    /// </remarks>\n    /// <param name=\"builder\">The <see cref=\"IApplicationBuilder\"/>.</param>\n    /// <returns>The app builder.</returns>\n    public static IApplicationBuilder UseAntiforgery(this IApplicationBuilder builder)\n    {\n        ArgumentNullException.ThrowIfNull(builder);\n        builder.VerifyAntiforgeryServicesAreRegistered();\n\n        builder.Properties[AntiforgeryMiddlewareSetKey] = true;\n        builder.UseMiddleware<AntiforgeryMiddleware>();\n\n        return builder;\n    }\n\n    private static void VerifyAntiforgeryServicesAreRegistered(this IApplicationBuilder builder)\n    {\n        if (builder.ApplicationServices.GetService(typeof(IAntiforgery)) == null)\n        {\n            throw new InvalidOperationException(\"Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddAntiforgery' in the application startup code.\");\n        }\n    }\n}\n","sourceCodeStart":36,"sourceCodeEnd":58,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/3600ca084e9c8b5f4174fc5e747f4c52d2100806/src/Antiforgery/src/AntiforgeryApplicationBuilderExtensions.cs#L36-L58","documentation":"UseAntiforgery middleware (the .NET 9+ built-in antiforgery middleware) requires that the IAntiforgery service is registered in the DI container. Before wiring the middleware it probes ApplicationServices for IAntiforgery and throws this if absent, telling you to call AddAntiforgery in startup.","triggerScenarios":"Calling builder.UseAntiforgery() (AntiforgeryApplicationBuilderExtensions.cs:39-48) when no service has registered IAntiforgery - i.e. AddAntiforgery(), AddMvc(), AddControllers(), or AddRazorPages() was not called on IServiceCollection beforehand.","commonSituations":"Minimal API or raw app that calls UseAntiforgery() but only added the antiforgery services conditionally or not at all; services registered after the middleware pipeline is built; moving to the new middleware from an older code path that implicitly registered services.","solutions":["Call builder.Services.AddAntiforgery() (or AddMvc/AddControllers/AddRazorPages) before app.Build()/UseAntiforgery().","Verify the registration is on the same IServiceCollection that builds the app pipeline.","If using AddControllers minimal setup, ensure AddControllers() (which registers antiforgery) runs before the middleware."],"exampleFix":"// before\nvar app = builder.Build();\napp.UseAntiforgery(); // throws - no service\n// after\nbuilder.Services.AddAntiforgery();\nvar app = builder.Build();\napp.UseAntiforgery();","handlingStrategy":"validation","validationCode":"// Verify registration before building the pipeline\nif (!builder.Services.Any(s => s.ServiceType == typeof(Microsoft.AspNetCore.Antiforgery.IAntiforgery))) {\n    builder.Services.AddAntiforgery();\n}","typeGuard":"bool antiforgeryRegistered = builder.Services.Any(s => s.ServiceType == typeof(IAntiforgery));","tryCatchPattern":"try {\n    app.UseAntiforgery();\n} catch (InvalidOperationException ex) when (ex.Message.Contains(\"AddAntiforgery\")) {\n    builder.Services.AddAntiforgery(); // then rebuild app\n    throw;\n}","preventionTips":["Call AddAntiforgery() (or AddMvc/AddControllers/AddRazorPages) before app.Build().","Register services on the same IServiceCollection that builds the pipeline.","Add a startup smoke test that resolves IAntiforgery from the root provider."],"tags":["csharp","dotnet","aspnetcore","antiforgery","dependency-injection","middleware"],"backgroundTag":null,"analyzedSha":"3600ca084e9c8b5f4174fc5e747f4c52d2100806","analyzedAt":"2026-08-11T16:32:30.678Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}