asp.net标识核心-与角色相关的查询太多

ttisahbt  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(450)

我的项目使用基于角色的授权,它有100多个角色。我注意到,在每个操作之前,服务器都会分别查询每个用户角色及其声明。在每个操作之前有200多个查询。即使一个空的控制器也能做到这一点,所以我假设这是asp.net身份核心功能。有没有办法优化这个?
提前谢谢。

  1. ASP.NET Core web server output (one out of many role queries):
  2. info: Microsoft.EntityFrameworkCore.Database.Command[20101]
  3. Executed DbCommand (1ms) [Parameters=[@__role_Id_0='390'], CommandType='Text', CommandTimeout='30']
  4. SELECT [rc].[ClaimType], [rc].[ClaimValue]
  5. FROM [AspNetRoleClaims] AS [rc]
  6. WHERE [rc].[RoleId] = @__role_Id_0
  7. info: Microsoft.EntityFrameworkCore.Database.Command[20101]
  8. Executed DbCommand (1ms) [Parameters=[@__normalizedName_0='100' (Size = 256)], CommandType='Text', CommandTimeout='30']
  9. SELECT TOP(1) [r].[Id], [r].[ConcurrencyStamp], [r].[Name], [r].[NormalizedName]
  10. FROM [AspNetRoles] AS [r]
  11. WHERE [r].[NormalizedName] = @__normalizedName_0

我的startup.cs类:

  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration)
  4. {
  5. Configuration = configuration;
  6. }
  7. public IConfiguration Configuration { get; }
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. public void ConfigureServices(IServiceCollection services)
  10. {
  11. services.Configure<CookiePolicyOptions>(options =>
  12. {
  13. // This lambda determines whether user consent for non-essential cookies
  14. // is needed for a given request.
  15. options.CheckConsentNeeded = context => true;
  16. options.MinimumSameSitePolicy = SameSiteMode.None;
  17. });
  18. services.AddRouting(options => options.LowercaseUrls = true);
  19. services.AddDistributedMemoryCache();
  20. services.AddSession(options =>
  21. {
  22. options.IdleTimeout = TimeSpan.FromDays(1);
  23. options.Cookie.IsEssential = true;
  24. });
  25. services.AddDbContext<AppDbContext>(options =>
  26. options
  27. .EnableSensitiveDataLogging()
  28. .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), x =>
  29. {
  30. x.UseRowNumberForPaging();
  31. x.UseNetTopologySuite();
  32. }));
  33. services.Configure<WebEncoderOptions>(options =>
  34. {
  35. options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
  36. });
  37. services.Configure<AppConfiguration>(
  38. Configuration.GetSection("AppConfiguration"));
  39. services.AddIdentity<User, UserRole>()
  40. .AddEntityFrameworkStores<AppDbContext>()
  41. .AddDefaultTokenProviders();
  42. services.Configure<IdentityOptions>(options =>
  43. {
  44. // Password settings
  45. options.Password.RequireDigit = true;
  46. options.Password.RequiredLength = 8;
  47. options.Password.RequireNonAlphanumeric = false;
  48. options.Password.RequireUppercase = true;
  49. options.Password.RequireLowercase = false;
  50. options.Password.RequiredUniqueChars = 6;
  51. // Lockout settings
  52. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
  53. options.Lockout.MaxFailedAccessAttempts = 10;
  54. options.Lockout.AllowedForNewUsers = true;
  55. // User settings
  56. options.User.RequireUniqueEmail = true;
  57. });
  58. services.Configure<SecurityStampValidatorOptions>(options =>
  59. {
  60. // enables immediate logout, after updating the users stat.
  61. options.ValidationInterval = TimeSpan.Zero;
  62. });
  63. services.ConfigureApplicationCookie(options =>
  64. {
  65. // Cookie settings
  66. options.Cookie.HttpOnly = true;
  67. options.Cookie.Expiration = TimeSpan.FromDays(150);
  68. // If the LoginPath isn't set, ASP.NET Core defaults
  69. // the path to /Account/Login.
  70. options.LoginPath = "/Account/Login";
  71. // If the AccessDeniedPath isn't set, ASP.NET Core defaults
  72. // the path to /Account/AccessDenied.
  73. options.AccessDeniedPath = "/Account/AccessDenied";
  74. options.SlidingExpiration = true;
  75. });
  76. // Add application services.
  77. services.AddScoped<IEmailSenderService, EmailSenderService>();
  78. services.AddScoped<IUploaderService, UploaderService>();
  79. services.AddScoped<IPdfService, PdfService>();
  80. services.AddScoped<ICurrencyRateService, CurrencyRateService>();
  81. services.AddScoped<IViewRenderService, ViewRenderService>();
  82. services.AddScoped<IUserCultureInfoService, UserCultureInfoService>();
  83. services.AddScoped<IUserService, UserService>();
  84. services.AddHostedService<QueuedHostedService>();
  85. services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
  86. services
  87. .AddMvc(options =>
  88. {
  89. options.EnableEndpointRouting = false;
  90. options
  91. .RegisterDateTimeProvider(services)
  92. .ModelMetadataDetailsProviders
  93. .Add(new BindingSourceMetadataProvider(typeof(ListFilterViewModel), BindingSource.ModelBinding));
  94. })
  95. .AddSessionStateTempDataProvider()
  96. .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  97. }
  98. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  99. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  100. {
  101. if (env.IsDevelopment())
  102. {
  103. app.UseDeveloperExceptionPage();
  104. app.UseDatabaseErrorPage();
  105. // app.UseMiddleware<StackifyMiddleware.RequestTracerMiddleware>();
  106. }
  107. else
  108. {
  109. # if DEBUG
  110. app.UseDeveloperExceptionPage();
  111. # else
  112. app.UseExceptionHandler("/Default/Error");
  113. # endif
  114. app.UseHsts();
  115. }
  116. app.UseHttpsRedirection();
  117. app.UseStaticFiles();
  118. app.UseSession();
  119. app.UseCookiePolicy();
  120. app.UseAuthentication();
  121. app.UseMvc(routes =>
  122. {
  123. routes.MapAreaRoute(
  124. name: "Hubs",
  125. areaName:"Hubs",
  126. template: "Hubs/{controller=CompanyAddresses}/{action=Index}/{id?}");
  127. routes.MapRoute(
  128. name: "areas",
  129. template: "{area:exists}/{controller=Default}/{action=Index}/{id?}"
  130. );
  131. routes.MapRoute(
  132. name: "default",
  133. template: "{controller=Default}/{action=Index}/{id?}");
  134. });
  135. }
  136. }
vawmfj5a

vawmfj5a1#

我已经找到了导致这种奇怪行为的原因。这是我的startup.cs类中的代码段:

  1. services.Configure<SecurityStampValidatorOptions>(options =>
  2. {
  3. // enables immediate logout, after updating the users stat.
  4. options.ValidationInterval = TimeSpan.Zero;
  5. });

去掉它解决了我的问题。我一直在使用它来强制注销用户,方法是更新他们的安全戳,如下所述:如何在asp.net核心标识中注销其他用户
似乎我将不得不寻找其他解决方案来强制注销,但我很高兴请求现在没有生成数百个sql查询。

相关问题