加载不同的服务是Startup.cs基于Endpoint或URL Path的ConfigureServices

问题描述 投票:0回答:1

我尝试根据我正在使用的端点或 URL 路径(以更容易的为准)加载不同的服务。

示例:
如果 URL/端点是 ...

Foo/Bar/
-- 加载第一组服务
如果 URL/端点是 ...
Foo/
-- 加载第二组服务

这是我的代码

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            var graphBaseUrl = Configuration["Graph:BaseUrl"]; //"https://graph.microsoft.com/v1.0";

            var userReadScope = "user.read";

            var Bar= "true";

            // List of scopes required
            string[] initialScopes = new string[] { userReadScope };


            if (Bar == "false")
            {
                services.AddMvc()
                    .AddSessionStateTempDataProvider();
                services.AddSession();
            }
            else
            {
                services.AddMicrosoftIdentityWebAppAuthentication(Configuration, configSectionName: "ABC")
                    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                    .AddMicrosoftGraph(graphBaseUrl, userReadScope)
                    .AddSessionTokenCaches();

                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                        .RequireAuthenticatedUser()
                        .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).AddMicrosoftIdentityUI();
            }

            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseSession();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(async endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Site}/{id?}"
                    );
                    endpoints.MapRazorPages();
                }
            );
            app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "Bar",
                        pattern: "{controller=Bar}/{action=Index}/{id?}"
                    );
                    endpoints.MapRazorPages();
                }
            );
        }

我有一个“硬编码”变量

var Bar = "true";

并且代码和逻辑有效。我需要的是根据端点或 URL 路径(如果它包含路径 /Bar)动态设置“Bar”变量,甚至只是在未使用默认端点的情况下?

我尝试使用 services.AddHttpContextAccessor();但我所有的尝试都失败了。

c# asp.net url path endpoint
1个回答
0
投票

服务建立后。你无法改变。因此,您必须注册所有需要的服务,然后在处理管道中执行某些操作。
对于身份验证,您可以使用控制器或操作顶部的属性

[Authorize(AuthenticationSchemes ="xxxxx")]
来指定其使用的身份验证方法。每个身份验证方法都有一个“方案名称”。有时它们是隐藏的,你需要把它们挖出来。

对于 MASL,方案名称为

"OpenIdConnect"
或者您可以使用
OpenIdConnectDefaults.AuthenticationScheme

对于内置身份,方案名称为

"Identity.Application"

在您的 MASL 代码中,

AddControllersWithViews
部分创建一个选项,将此方案应用于每个操作。您需要删除该选项。 这就是我的示例项目program.cs的样子

//MASL authentication part.
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllersWithViews().AddMicrosoftIdentityUI(); 


//the build-in authentication service part
builder.Services.AddDbContext<ApplicationContext>();
builder.Services.AddIdentity<User, IdentityRole>()
 .AddEntityFrameworkStores<ApplicationContext>();

然后我对不同的动作使用不同的方案。 “隐私”apge 使用 MASL(“openidconnect”),“员工”页面使用内置方案。

测试结果。您可以看到“隐私”和“员工”要求不同的身份验证方法。

同样,在栏控制器顶部添加授权将适用于整个控制器。

© www.soinside.com 2019 - 2024. All rights reserved.