sam360
sam360

Reputation: 1131

ASP.NET 5 access context or request information at ConfigureServices in Startup class

Is it possible to access Context or Request information at the time ConfigureServices method is called in the Startup class?

What I would like to do is to decide what Facebook or MS authentication info to load from Database based on URL or other request info.

public void ConfigureServices(IServiceCollection services)
    {
        // Add Entity Framework services to the services container.
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        // Add Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Configure the options for the authentication middleware.
        // You can add options for Google, Twitter and other middleware as shown below.
        // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
        services.Configure<FacebookAuthenticationOptions>(options =>
        {
            options.AppId = Configuration["Authentication:Facebook:AppId"];
            options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
        });

        services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
        {
            options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
            options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
        });

...

Upvotes: 2

Views: 1348

Answers (2)

Henk Mollema
Henk Mollema

Reputation: 46551

The current HttpContext is set by the hosting engine.

A few lines before that the engine builds the application, that means ConfigureServices and Configure are already called before the HttpContext is available.

This makes sense, because the application configuration in the Startup class is only called when the application starts, not every request.

Upvotes: 1

Rytmis
Rytmis

Reputation: 32047

Startup is for configuration that happens once per application, not once per request. If you need to do something on a per-request basis, you should either do it in a MVC/API controller or middleware.

Upvotes: 1

Related Questions