0

I try to add conditionally an OperationProcessor in NSwag. For example, the DefaultApiValueOperationProcessor should only be added/enabled when we are in a development environment (env.IsDevelopment)

Unfortunately I can't retrieve IHostingEnvironment in ConfigureServices, and also I can't get the Swagger's OperationProcessors on Configure, see code example at the comment lines:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSwaggerDocument(s =>
        {
            // can't get IHostingEnvironment here? (for env.IsDevelopment())

            s.OperationProcessors.Add(new DefaultApiValueOperationProcessor("version", "1"));
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // can't get Swagger's OperationProcessors here?

        app.UseOpenApi();
        app.UseSwaggerUi3(o =>
        {
            o.DocExpansion = "list";
            o.DocumentTitle = "My API";
        });

        app.UseMvc();
    }
}

Any idea how I could fix this?

Julian
  • 33,915
  • 22
  • 119
  • 174

1 Answers1

1

To access the web host environment from ConfigureServices, simply add a WebHostEnvironment property to the Startup class and set it from the constructor:

public class Startup
{
    private IConfiguration Configuration { get; }
    private IWebHostEnvironment WebHostEnvironment { get; }

    public Startup(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
    {
        Configuration = configuration;
        WebHostEnvironment = webHostEnvironment;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        if (WebHostEnvironment.IsDevelopment())
        {
            // ...
        }
    }
}

I also put the Configuration property in this example because a lot of programs need it anyway.

Please note that the type is IWebHostEnvironment and not IWebHostingEnvironment because the latter has been deprecated.

Regarding your second question (how to access the operation processor from Configure), could you please shed a light on your intentions? I have no idea what you're trying to achieve.

Sandor Drieënhuizen
  • 6,310
  • 5
  • 37
  • 80
  • Thanks! The second question would be another way to fix this, but one good solution is enough :) – Julian Apr 18 '20 at 02:51