我遇到了这个问题,我已经挠头好几个小时了。
问题:我创建的会话状态Login
拨打电话后神秘清除或丢失API
.NET CORE 2.1 中也包含控制器。当我打电话时会发生这种情况API
方法看起来像:
[Authorize(Policy = "AdminViewPolicy")]
[HttpGet("GetAllUsersId")]
public IActionResult GetAllUsersId()
{
var user = _userService.GetAllUsersId();
return Ok(new
{
data = user
});
}
此方法的角色和其他方面工作正常。这就是我调用此操作方法的方式:
$.ajax({
url: "https://www.someworkingwebsite.com/api/Users/GetAllUsersId",
type: "GET",
async: false,
dataType: "json",
contentType: "application/json",
data: {},
credentials: 'include',
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", window.localStorage.getItem("authToken"));
},
success: function (data) {
console.log(data);
var html = [];
for (var i in data["data"]) {
var id = data["data"][i]["fullName"] + "###" + data["data"][i]["uuid"] + "###" + data["data"][i]["id"];
//var id = data["data"][i]["uuid"] + "###" + data["data"][i]["id"];
html.push(id);
}
/*initiate the autocomplete function on the "searchInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("searchInput"), html);
},
error: function () {
console.log("Error" + data);
},
});
我的 Startup.cs 配置为API
项目看起来像:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
services.AddMvc(options =>
{
options.Filters.Add(typeof(ValidateModelAttribute));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpContextAccessor();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//Other code omitted for brevity
app.UseForwardedHeaders();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseAuthentication();
app.UseSession();
}
我的客户端过滤器用于检查Session
好像:
public override void OnActionExecuting(ActionExecutingContext context)
{
if (Context.Current.Session == null || !Context.Current.Session.TryGetValue("UserID", out byte[] val))
{
context.Result =
new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "Pages",
action = "SessionTimeout"
}));
}
base.OnActionExecuting(context);
}
事情变得棘手的部分。当我从我的设备调用 AJAX 函数时View
,AJAX成功调用API
方法并获取所需的数据,而且 AJAX 调用也会以某种方式清除我的会话,因为一旦我导航到其他页面或提交表单,SessionTimeout
上面显示的属性被调用,我被踢出了系统。
我检查了网络浏览器上的所有控制台日志、网络请求、应用程序存储,但找不到罪魁祸首。我还检查了 API 和客户端中的逻辑,看看我是否犯了这个重大错误,但我找不到任何暗示这一点的东西。
自从API
并且客户端托管在 IIS 服务器上,我想也许那个该死的环境可以做一些事情,但不,我也找不到任何人可以责怪那里。
经过一番折腾后,我终于决定向专业人士请教。如果有人能帮助我那就太好了hopefully
解决我的这个问题。
感谢期待。