簡體   English   中英

Session 數據被接收 NULL 從一種方法到另一種方法 asp.net 核心 3

[英]Session data is received NULL from one method to another method asp.net core 3

我有一個 ASP.NET 核心 3.1 web API 應用程序。 I am trying to store the string value in session, when call the method that is set string in Session from client side it' fine and stored the value, but when I call another method for Get String from session that is null. 請幫我解決它。

啟動配置服務:

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.Cookie.Name = "AdventureWorks.Session";
            options.IdleTimeout = TimeSpan.FromMinutes(20);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true; // make the session cookie Essential
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddMvc();
   }

    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {

        app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); 

        app.UseCors(_defaultCorsPolicyName); // Enable CORS!

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAbpRequestLocalization();

        app.UseSession();

        app.UseEndpoints();
  }

設置字符串的方法:

 public async Task<FileStreamResult> GetCaptchaImage()
 {  

        Captcha.Captcha captcha = new Captcha.Captcha();
        int width = 100;
        int height = 36;
        var captchaCode = captcha.GenerateCaptchaCode();
        var result = captcha.GenerateCaptchaImage(width, height, captchaCode);
        _httpContextAccessor.HttpContext.Session.SetString("CaptchaCode", result.CaptchaCode);
        Stream s = new MemoryStream(result.CaptchaByteData);
        return new FileStreamResult(s, "image/png");
   }

獲取字符串的方法:

 public bool ValidateCaptchaCode(string userInputCaptcha)
    {
        var captchaValueInSession = _httpContextAccessor.HttpContext..GetString("CaptchaCode");
        var isValid = userInputCaptcha == captchaValueInSession;
        _httpContextAccessor.HttpContext.Session.Remove("CaptchaCode");
        return isValid;
    }

是 NULL

var captchaValueInSession = _httpContextAccessor.HttpContext.Session.GetString("CaptchaCode");

如何從另一種方法獲得 Session 值

還可以在前端驗證驗證碼,而不是在 api

string rr = HttpContext.Session.GetString("CaptchaCode");
                if (model.captchacode != rr)
                {
                    ModelState.AddModelError(string.Empty, "Enter Valid Captcha");
                }

暫無
暫無

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

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