为什么会话变量在异步请求中为空?



我正在 .NET Core 3 上使用会话变量,当我发出异步请求来检查这些变量(来自 angularjs(时,它们会变成空值(对于同步请求,我可以获取这些值(。

这是我的设置.cs

public void ConfigureServices(IServiceCollection services)
{
string[] origins = new string[1] { "http://angularapp" };
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins(origins)
.AllowAnyHeader()
.AllowCredentials());
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IClaimPrincipalManager, ClaimPrincipalManager>();
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.Cookie.IsEssential = true;
});
services.AddControllersWithViews(); 
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseCors("AllowMyOrigin");
app.UseRouting();
app.UseAuthorization();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}

这是我尝试从会话中获取一个值的地方

#region Private Fields
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
#endregion Private Fields
#region Public Constructors
public SecurityController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task<IActionResult> IsSessionActive()
{
try
{
var user = await _session.Get<string>("User");
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
return Ok(true);
}

这是我的Asyn调用(AngularJS(

$http({
method: "POST",
url: BACKEND_URL,
withCredetial: true,
headers: [
{ 'Content-Type': 'application/json' }
]
}).then(function (response) {
console.log(response);
});

顺便说一下,我正在使用方法会话。LoadAsync((通过实现此扩展

public static class SessionExtensions
{
public static async Task Set<T>(this ISession session, string key, T value)
{
if (!session.IsAvailable)
await session.LoadAsync();
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static async Task<T> Get<T>(this ISession session, string key)
{
if (!session.IsAvailable)
await session.LoadAsync();
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}

TYPO:

$http({
method: "POST",
url: BACKEND_URL,
̶w̶i̶t̶h̶C̶r̶e̶d̶e̶t̶i̶a̶l̶:̶ ̶t̶r̶u̶e̶,̶
withCredentials: true,
headers: ̶[̶
{ 'Content-Type': 'application/json' }
̶]̶
}).then(function (response) {
console.log(response);
});

有关详细信息,请参阅

  • AngularJS $http服务 API 参考 - 参数

最新更新