Home > Mobile >  ASP.NET Core - 'Configuration.GetSection(string)' Error in Swagger Implementation
ASP.NET Core - 'Configuration.GetSection(string)' Error in Swagger Implementation

Time:01-04

In my ASP.NET Core Web API-5.0, I am implementing Swagger. I have this:

using System.Configuration;

public static class SwaggerExtension
{
    public static IApplicationBuilder UseVersionedSwagger(this IApplicationBuilder app, IApiVersionDescriptionProvider provider)
    {
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();
        string virDir = Configuration.GetSection("VirtualDirectory").Value;
        app.UseSwaggerUI(
            options =>
            {
                // build a swagger endpoint for each discovered API version
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerEndpoint(virDir   "/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                }
            });

        return app;
    }
}

I got this error:

An object reference is required for the non-static field, method, or property 'Configuration.GetSection(string)'

And this line highlighted:

Configuration.GetSection

VirtualDirectory is referenced in appsettings.json

How do I get this resolved?

Thanks

CodePudding user response:

Change:

string virDir = Configuration.GetSection("VirtualDirectory").Value;

To something like:

string virDir = app.ApplicationServices.GetRequiredService<IConfiguration>().GetSection("VirtualDirectory").Value;

Configuration refers to nothing which is why you're getting the error. You need to pass an IConfiguration instance, or get it from the servicecontainer like i have done.

You may also want to add exta null/empty string checks to be sure your configuration is right.

CodePudding user response:

The method Configuration.GetSection return an object of type IConfigurationSection if I remember correctly. And you try to store it in a string object, it's not possible.

Try to do that :

var virDir = Configuration.GetSection("VirtualDirectory").Value;

If it works, you can after check exactly which object type is returned by "GetSection" method with a mouse hover on it, and change "var" with the correct type : hover a method for check the returned type

Regards.

  •  Tags:  
  • Related