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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.