Razor 处理帖子上的会话状态超时

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

我在 Razor Web 应用程序中使用带有 cookie 的会话状态 文档说如果 cookie 超时,会话将在服务器中恢复

如果收到过期会话的 cookie,则会创建一个使用相同会话 cookie 的新会话。

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-7.0#session-state

当 cookie 超时(或者我删除它)并重新加载页面时,它会起作用,状态会被保留

但问题是,我使用大量 Ajax 来进行部分页面加载,并且当我通过 ajax 调用 POST 处理程序时,状态不会保留

是否有办法使 POST 的行为与 GET 的行为相同,以便恢复会话状态?

c# asp.net-core razor session-cookies
1个回答
0
投票

我不太确定我的测试结果是否与你的相符...

我有一个剃刀网络应用程序,这是我的视图和操作代码。

@page
@model WebAppRazor.Pages.Clients.IndexModel
@Html.AntiForgeryToken()
@{
}

<div>this is clients/index</div>
<a class='btn btn-primary btn-sm' href='/Clients/Create'>New Client</a>

<button onclick="postdata()">Abc</button>
<input type="text" id="sessionInfo"></input>

@section Scripts{
    <script>
        function postdata() {
            $.ajax({
                type: "POST",
                url: '/clients/index?handler=Abc',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                data: {
                    id: "asdf"
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    // alert('Success!');
                    console.info(data);
                    $('#sessionInfo').val(data);
                }
            });
        }
    </script>
}

public class IndexModel : PageModel
{
    public const string SessionKeyName = "_Name";
    public const string SessionKeyAge = "_Age";

    public void OnGet()
    {
        var sessionId = HttpContext.Session.Id;
        
        
        
        if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
        {
            HttpContext.Session.SetString(SessionKeyName, "UserA");
            HttpContext.Session.SetInt32(SessionKeyAge, 18);
        }
        var name = HttpContext.Session.GetString(SessionKeyName);
        var age = HttpContext.Session.GetInt32(SessionKeyAge).ToString();
    }

    
    public IActionResult OnPostAbc(string id)
    {
        var sessionId = HttpContext.Session.Id;
        var name = HttpContext.Session.GetString(SessionKeyName);
        var age = HttpContext.Session.GetInt32(SessionKeyAge).ToString();
        return new JsonResult(name + age);
    }

}

程序.cs

builder.Services.AddDistributedMemoryCache();

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(5);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});
builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
...
...
app.UseRouting();

app.UseAuthorization();

app.UseSession();

app.MapRazorPages();

这是我的测试结果。

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