In a asp.net core web api middleware, is it possible to access the configuration inside the middleware? Can someone guide me how this is done?
In ASP.NET Core, the code in the various initialization files in the Startup folder and the XML in the app. config file are gone, collapsed into the code in the Startup class in your project's Startup. cs file.
Configuring the Request Pipeline To start using any Middleware, we need to add it to the Request pipeline. This is done in the Configure method of the startup class. The Configure method gets the instance of IApplicationBuilder, using which we can register our Middleware.
The web. config file has also been replaced in ASP.NET Core. Configuration itself can now be configured, as part of the application startup procedure described in Startup.
ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of ASP.NET applications. Configuration files help you to manage the many settings related to your website. Each file is an XML file (with the extension . config) that contains a set of configuration elements.
In a middle-ware
you can access settings. To achieve this, you need to get IOptions<AppSettings>
in the middle-ware
constructor. See following sample.
public static class HelloWorldMiddlewareExtensions
{
public static IApplicationBuilder UseHelloWorld(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<HelloWorldMiddleware>();
}
}
public class HelloWorldMiddleware
{
private readonly RequestDelegate _next;
private readonly AppSettings _settings;
public HelloWorldMiddleware(
RequestDelegate next,
IOptions<AppSettings> options)
{
_next = next;
_settings = options.Value;
}
public async Task Invoke(HttpContext context)
{
await context.Response.WriteAsync($"PropA: {_settings.PropA}");
}
}
public class AppSettings
{
public string PropA { get; set; }
}
For more information see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With