I put the code in a separate extending method, but ide doesn't see it. I'm getting next error 'IServiceCollection' does not contain a definition for 'AddSwagger' and no accessible extension method 'AddSwagger' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) What could be the reason?
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwagger();
builder.Services.AddProblemDetails();
...
}
public static IServiceCollection AddSwagger(this IServiceCollection services)
{
return services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Description = "Standard Authorization header using the Bearer scheme (\"Bearer {token}\")",
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
}
}
If I move the method to another class, then everything works fine. Why?
For an extension method, the class containing it also has to be marked as
static.From your example it appears that the
AddSwaggermethod is withinProgramclass which isn't markedstatic. You would need to move theAddSwaggermethod to another class that is marked static.For more information look at this - How to implement and call a custom extension method