我正在做一个.Net6 razor页面项目,我正在使用会话来存储变量.我有一个页面,可以编辑XML"文档"(DispatchAdvise-供您参考),并将模型对象存储在会话中,以便管理此文档子列表上的CRUD操作.
这是我的创业计划.配置会话的cs
public void ConfigureServices(IServiceCollection services)
{
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;
});
//*** Other settings omitted ***
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(Configuration.GetValue<int>("SessionTimeoutInMinutes"));
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.IsEssential = true;
options.Cookie.Name = "_aspnetCoreSession";
});
services.AddHttpContextAccessor();
//*** Other settings omitted ***
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment() || env.IsStaging())
{
app.UseDeveloperExceptionPage();
RegisteredServicesPage(app); //create a custom page with every service registered
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseSession();
app.UseAuthorization();
app.UseMvc();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
我有一个为会话创建扩展方法的类
public static class SessionUtils
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
session.CommitAsync().Wait(); //added to see if something changed (no success)
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
session.LoadAsync().Wait();//added to see if something changed (no success)
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value, new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace });
}
}
The two methods CommitAsync and LoadAsync doesn't helped me a lot :(
现在我的问题是...
Note: Load and Save methods are handled using AJAX. Load by DataTables ajax call and Save with a normal AJAX call
下面是将对象列表返回到datatables的代码以及在会话中保存的方法.
public JsonResult OnPostLoadDriversDA()
{
Utils_CommonResponse resp = new Utils_CommonResponse();
List<DespatchAdviceAdditionaDocumentReference> ListIdDocumentRefDriver = new List<DespatchAdviceAdditionaDocumentReference>();
try
{
DespatchAdviceDettaglio = HttpContext.Session.GetObjectFromJson<DespatchAdviceDettaglio>("DespatchAdviceDettaglio");
List<DocumentReferenceType> IdDriver = DespatchAdviceDettaglio.DespatchAdvice.Shipment.Consignment[0].CarrierParty.Person[0].IdentityDocumentReference;
if (IdDriver.Count > 0 && String.IsNullOrEmpty(IdDriver.First().ID.Value))
{
//Here I reset the list because I have an empty object to create the interface but for datatables must be an empty list
IdDriver = new List<DocumentReferenceType>();
DespatchAdviceDettaglio.DespatchAdvice.Shipment.Consignment[0].CarrierParty.Person[0].IdentityDocumentReference = IdDriver;
//Here the object IdentityDocumentReference has 0 items (IdDriver is a new List - the problem is on save method)
HttpContext.Session.SetObjectAsJson("DespatchAdviceDettaglio", DespatchAdviceDettaglio);
}
foreach (DocumentReferenceType drf in IdDriver)
{
ListIdDocumentRefDriver.Add(new DespatchAdviceAdditionaDocumentReference()
{
ID = drf.ID.Value,
TipoDocumento = drf.DocumentType.Value
});
}
return new JsonResult(new
{
DataTablesRequest.Draw,
recordsFiltered = ListIdDocumentRefDriver.Count,
data = ListIdDocumentRefDriver
});
}
catch (Exception exc)
{
_logger.LogError($"{exc.Message} - {exc.StackTrace}");
resp.Esito = false;
resp.Messaggio = exc.Message;
return new JsonResult(resp);
}
}
在会话中保存数据的方法
public JsonResult OnPostSaveDriveDA([FromBody] SaveDriver IncomingData)
{
Utils_CommonResponse resp = new Utils_CommonResponse();
try
{
DespatchAdviceDettaglio = HttpContext.Session.GetObjectFromJson<DespatchAdviceDettaglio>("DespatchAdviceDettaglio");
if (IncomingData.IdDriver == -1)
{
//Here, after loading "DespatchAdviceDettaglio" from session, SOMETIMES the list IdentityDocumentReference has 1 element (the empty one)
DespatchAdviceDettaglio.DespatchAdvice.Shipment.Consignment[0].CarrierParty.Person[0].IdentityDocumentReference.Add(IncomingData.DocRefDriver);
}
else
{ //edit
DespatchAdviceDettaglio.DespatchAdvice.Shipment.Consignment[0].CarrierParty.Person[0].IdentityDocumentReference[IncomingData.IdDriver] = IncomingData.DocRefDriver;
}
HttpContext.Session.SetObjectAsJson("DespatchAdviceDettaglio", DespatchAdviceDettaglio);
resp.Esito = true;
resp.Messaggio = "";
}
catch (Exception exc)
{
resp.Esito = false;
resp.Messaggio = exc.Message;
}
return new JsonResult(resp);
}
正如我在上面的 comments 中所写的,在OnPostSaveDriveDA中,我从会话中获得的对象是"旧对象".然后,新驱动程序将添加到列表中.但当我重新加载列表时,我会丢失所有项目,因为第一个项目显然是空的,所以列表会重置.
这让我大吃一惊,因为它并不是每次都发生.
是否有人有同样的问题或知道如何解决,并告诉我为什么会发生这种情况?
谢谢所有能帮助我的人.