Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net core 2.0 middleware - accessing config settings

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?

like image 942
Skadoosh Avatar asked Dec 08 '17 22:12

Skadoosh


People also ask

Where is configuration information in ASP.NET Core?

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.

How can we configure the pipeline for middleware?

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.

Does ASP.NET Core have web config?

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.

What is Aspnet config?

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.


1 Answers

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.

like image 81
Afshar Mohebi Avatar answered Nov 08 '22 18:11

Afshar Mohebi