簡體   English   中英

如何在用戶 OnSignedIn 事件啟動時創建 Redis 緩存?

[英]How to create a Redis cache in startup on user OnSignedIn event?

.NET 核心 3.1

我得到了如何從 Identity Server 注銷所有客戶端的答案

我通過這個例子(章節)REVOCATION 工作。

但現在我有一個新問題。 在 OnSignedIn 事件中,我想將用戶 ID 添加到 Redis 緩存,但我不知道如何添加。

這是一個不好的做法:

var sp = services.BuildServiceProvider();
var cache = sp.GetService<IDistributedCache>();
cache.SetString("helloFromRedis", "world");
var valueFromRedis = cache.GetString("helloFromRedis");
Console.WriteLine(valueFromRedis);

我的啟動.cs

public class Startup
{
   public Startup(IConfiguration configuration)
   {
       Configuration = configuration;
   }

   public IConfiguration Configuration { get; }

   public void ConfigureServices(IServiceCollection services)
   {
     services.AddStackExchangeRedisCache(options =>
     {
        options.Configuration = RedisString;
     });


     services.AddAuthentication(options =>
     {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";                              
     })
      .AddCookie("Cookies", options =>
      {
         options.Cookie.HttpOnly = true;                   
         options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
         options.SlidingExpiration = true;
         options.Events.OnSignedIn(a => {
               // there I want to resolve cache and put userId from claims.
         });
      })
      .AddOpenIdConnect("oidc", options =>
       {
        //...
      });
   }

我如何解決Redis緩存?

你可以這樣做:

o.Events.OnSignedIn = ctx =>
{
    var cache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
    return  Task.CompletedTask;
};

RequestServices屬性是IServiceProvider一個實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM