【问题标题】:ASP.NET 5 access context or request information at ConfigureServices in Startup classASP.NET 5 在 Startup 类的 ConfigureServices 访问上下文或请求信息
【发布时间】:2015-08-14 11:54:23
【问题描述】:

是否可以在 Startup 类中调用 ConfigureServices 方法时访问 Context 或 Request 信息?

我想做的是根据 URL 或其他请求信息决定从数据库加载哪些 Facebook 或 MS 身份验证信息。

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"];
        });

...

【问题讨论】:

    标签: c# asp.net asp.net-core


    【解决方案1】:

    启动是针对每个应用程序发生一次的配置,而不是每个请求一次。如果您需要基于每个请求执行某项操作,您应该在 MVC/API 控制器或中间件中执行此操作。

    【讨论】:

    • 在这种情况下,我们可以在 ConfigureServices 方法之外注册 Facebook 和 MS 身份验证服务吗?因为如果你想让它成为多租户,它们在预建模板中的方式是没有用的!
    • 您是在说一个租户拥有 FB 身份验证,而另一个租户拥有 MS 身份验证,但不能同时拥有两者的情况?
    • 不,更多的是 FB 或 MS 的凭据(令牌等)会因租户而异。
    • 在这种情况下,我怀疑您最好的选择是编写可以考虑到这一点的中间件的修改版本。
    【解决方案2】:

    当前HttpContexthosting engine设置。

    在引擎构建应用程序之前的few lines,这意味着在HttpContext 可用之前已经调用了ConfigureServicesConfigure

    这是有道理的,因为Startup 类中的应用程序配置仅在应用程序启动时调用,而不是每个请求。

    【讨论】:

    • 在这种情况下,我们可以在 ConfigureServices 方法之外注册 Facebook 和 MS 身份验证服务吗?因为如果你想让它成为多租户,它们在预建模板中的方式是没有用的!
    猜你喜欢
    • 2023-03-17
    • 2018-05-12
    • 2016-04-12
    • 2018-05-25
    • 2011-06-07
    • 1970-01-01
    • 2019-10-18
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多