第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何將基于角色的身份添加到 Razor Pages 應(yīng)用程序?

如何將基于角色的身份添加到 Razor Pages 應(yīng)用程序?

繁星淼淼 2022-12-24 12:56:13
我正在設(shè)置一個(gè)新的 Razor Pages 應(yīng)用,我想添加基于角色的授權(quán)。網(wǎng)絡(luò)上有很多教程如何使用 ASP.NET MVC 應(yīng)用程序而不是 Razor 頁面來完成。我嘗試了很少的解決方案,但對(duì)我沒有任何用處。目前我有一個(gè)問題如何為數(shù)據(jù)庫添加角色并將這個(gè)角色添加到每個(gè)新注冊(cè)用戶。這是我的Startup.cs樣子:public async Task ConfigureServices(IServiceCollection services){        var serviceProvider = services.BuildServiceProvider();        services.Configure<CookiePolicyOptions>(options =>        {            // This lambda determines whether user consent for non-essential cookies is needed for a given request.            options.CheckConsentNeeded = context => true;        });        services.AddDbContext<ApplicationDbContext>(options =>            options.UseSqlServer(                Configuration.GetConnectionString("DefaultConnection")));        services.AddDefaultIdentity<IdentityUser>(config =>        {            config.SignIn.RequireConfirmedEmail = true;        })            .AddRoles<IdentityRole>()            .AddDefaultUI(UIFramework.Bootstrap4)            .AddEntityFrameworkStores<ApplicationDbContext>();        services.AddAuthorization(config =>        {            config.AddPolicy("RequireAdministratorRole",                policy => policy.RequireRole("Administrator"));        });        services.AddTransient<IEmailSender, EmailSender>();        services.Configure<AuthMessageSenderOptions>(Configuration);        services.AddRazorPages()            .AddNewtonsoftJson()            .AddRazorPagesOptions(options => {                options.Conventions.AuthorizePage("/Privacy", "Administrator");            });        await CreateRolesAsync(serviceProvider);    }    }現(xiàn)在這段代碼拋出了一個(gè)異常:System.InvalidOperationException: '無法找到所需的服務(wù)。請(qǐng)通過在應(yīng)用程序啟動(dòng)代碼中對(duì)“ConfigureServices(...)”的調(diào)用中調(diào)用“IServiceCollection.AddAuthorizationPolicyEvaluator”來添加所有必需的服務(wù)。添加AddAuthorizationPolicyEvaluator沒有任何改變。有小費(fèi)嗎?
查看完整描述

1 回答

?
弒天下

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊

好的,我只是讓我的應(yīng)用程序正常工作 :) 我想我只是在這里發(fā)布我的Startup.cs代碼以備將來使用 - 也許它會(huì)對(duì)某人有所幫助。


public class Startup

{

    public Startup(IConfiguration configuration)

    {

        Configuration = configuration;

    }


    public IConfiguration Configuration { get; }


    // This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)

    {

        services.Configure<CookiePolicyOptions>(options =>

        {

            // This lambda determines whether user consent for non-essential cookies is needed for a given request.

            options.CheckConsentNeeded = context => true;

        });


        services.AddDbContext<ApplicationDbContext>(options =>

            options.UseSqlServer(

                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<IdentityUser>(config =>

        {

            config.SignIn.RequireConfirmedEmail = true;

        })

            .AddRoles<IdentityRole>()

            .AddDefaultUI(UIFramework.Bootstrap4)

            .AddEntityFrameworkStores<ApplicationDbContext>();


        services.AddAuthorization(config =>

        {

            config.AddPolicy("RequireAdministratorRole",

                policy => policy.RequireRole("Administrator"));

            config.AddPolicy("RequireMemberRole",

                policy => policy.RequireRole("Member"));

        });


        services.AddTransient<IEmailSender, EmailSender>();

        services.Configure<AuthMessageSenderOptions>(Configuration);


        services.AddRazorPages()

            .AddNewtonsoftJson()

            .AddRazorPagesOptions(options => {

                options.Conventions.AuthorizePage("/Privacy", "RequireAdministratorRole");

            });

    }


    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider, UserManager<IdentityUser> userManager)

    {

        if (env.IsDevelopment())

        {

            app.UseDeveloperExceptionPage();

            app.UseDatabaseErrorPage();

        }

        else

        {

            app.UseExceptionHandler("/Error");

            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

            app.UseHsts();

        }


        app.UseHttpsRedirection();

        app.UseStaticFiles();


        app.UseCookiePolicy();


        app.UseRouting();


        app.UseAuthentication();

        app.UseAuthorization();


        app.UseEndpoints(endpoints =>

        {

            endpoints.MapRazorPages();

        });


        CreateDatabase(app);

        CreateRolesAsync(serviceProvider).Wait();

        CreateSuperUser(userManager).Wait();

    }


    private async Task CreateSuperUser(UserManager<IdentityUser> userManager)

    {

        var superUser = new IdentityUser { UserName = Configuration["SuperUserLogin"], Email = Configuration["SuperUserLogin"] };

        await userManager.CreateAsync(superUser, Configuration["SuperUserPassword"]);

        var token = await userManager.GenerateEmailConfirmationTokenAsync(superUser);

        await userManager.ConfirmEmailAsync(superUser, token);

        await userManager.AddToRoleAsync(superUser, "Admin");

    }


    private void CreateDatabase(IApplicationBuilder app)

    {

        using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())

        {

            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

            context.Database.EnsureCreated();

        }

    }


    private async Task CreateRolesAsync(IServiceProvider serviceProvider)

    {

        //adding custom roles

        var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        string[] roleNames = { "Admin", "Member", "Outcast" };

        IdentityResult roleResult;


        foreach (var roleName in roleNames)

        {

            //creating the roles and seeding them to the database

            var roleExist = await RoleManager.RoleExistsAsync(roleName);

            if (!roleExist)

            {

                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));

            }

        }

    }

}

通常,應(yīng)用程序在啟動(dòng)時(shí)只是創(chuàng)建新數(shù)據(jù)庫,添加“Admin”、“Member”和“Outcast”角色,最后根據(jù)用戶機(jī)密憑據(jù)創(chuàng)建超級(jí)用戶帳戶。另外在Register.cshtml.cs文件中我有一行將默認(rèn)角色“成員”添加到新成員


    public async Task<IActionResult> OnPostAsync(string returnUrl = null)

    {

        returnUrl = returnUrl ?? Url.Content("~/");

        if (ModelState.IsValid)

        {

            var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };

            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)

            {

                _logger.LogInformation("User created a new account with password.");




                await _userManager.AddToRoleAsync(user, "Member");




                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var callbackUrl = Url.Page(

                    "/Account/ConfirmEmail",

                    pageHandler: null,

                    values: new { userId = user.Id, code = code },

                    protocol: Request.Scheme);


                await _emailSender.SendEmailAsync(Input.Email, "Confirm your email to get acces to Functionality Matrix pages",

                    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");


                // Block autologin after registration

                //await _signInManager.SignInAsync(user, isPersistent: false);

                return Redirect("./ConfirmEmailInfo");

            }

            foreach (var error in result.Errors)

            {

                ModelState.AddModelError(string.Empty, error.Description);

            }

        }


        // If we got this far, something failed, redisplay form

        return Page();

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-12-24
  • 1 回答
  • 0 關(guān)注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)