【发布时间】:2020-10-13 11:46:58
【问题描述】:
我刚开始使用 asp.net Core 3.1 并遇到了使用 Session 变量存储用户登录数据的问题,基本上它在页面之间切换或执行 ajax 发布时随机返回“null”。我花了几个小时在谷歌上搜索并尝试了我所看到的一切,但无济于事。我最终创建了一个新的 Razor 页面 Web 应用程序,但我仍然遇到会话变量返回 null 的问题。要重新生成此内容,请单击“保存更改”按钮,它将执行 HTTP Post,并且会话变量“索引”为空。
我希望有人可以在这里提供帮助。
<HTML>
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<script type="text/javascript">
$("body").on("click", ".Save", function (e) {
if (confirm("Do you want to Save all your changes?")) {
var bd = ["test:", "mike"];
$.ajax({
type: "POST",
url: "/Index?handler=Fred",
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(bd),
contentType: "application/json; charset=utf-8",
success: function (r) {
$("body").html(r);
alert("Update Completed");
},
error: function (result) { alert("error " + result.statusText) }
});
}
});
</script>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>first time to this page [ @ViewData["firsttime"].]</p>
<p>times to the page [ @ViewData["count"].]</p>
<p>session ID [ @HttpContext.Session.Id]</p>
<br />
<p>times posted [ @ViewData["post"].]</p>
<a class="Save btn btn-outline-danger btn-sm" href="javascript:;">Save Changes</a>
</div>
<HTML>
```
Startup.cs
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.AddDistributedMemoryCache();
services.AddSession(o =>
{
o.IdleTimeout = TimeSpan.FromMinutes(60);
o.Cookie.HttpOnly = true;
o.Cookie.IsEssential = true;
});
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
```
```Index.chtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System.Data;
namespace Grid.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
if (HttpContext.Session.GetString("Index") == null)
{
ViewData["firsttime"] = "yes";
ViewData["count"] = 1;
HttpContext.Session.SetInt32("Index", 1);
HttpContext.Session.SetInt32("Count", 1);
HttpContext.Session.SetInt32("Post", 0);
ViewData["post"] = 0;
}
else
{
ViewData["firsttime"] = "no";
int? i = HttpContext.Session.GetInt32("Count");
ViewData["count"] = i++;
ViewData["post"] = 0;
HttpContext.Session.SetInt32("Count", (int)i);
}
}
public void OnPostFred([FromBody] object bd)
{
if (HttpContext.Session.GetString("Index") == null)
{
int? i = HttpContext.Session.GetInt32("Post");
ViewData["post"] = i++;
HttpContext.Session.SetInt32("Post", (int)i);
}
else
{
ViewData["firsttime"] = "session gone";
}
}
}
}
```
【问题讨论】:
标签: asp.net asp.net-core