我正在.NET Core 3上使用Session变量,当我发出异步请求以检查这些变量(来自angularjs)时,它们变成空值(对于同步请求,我可以获取这些值)。
这是我的setup.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);
}
这是我的异步调用(angularjs)
$http({
method: "POST",
url: BACKEND_URL,
withCredetial: true,
headers: [
{ 'Content-Type': 'application/json' }
]
}).then(function (response) {
console.log(response);
});
顺便说一句,我通过实现此扩展名使用方法session.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);
});
有关更多信息,请参阅