Я не знаю, где это искать;Я новичок в ядре asp.net, и объект сеанса работал до сегодняшнего дня.
Вот мой класс запуска
public Startup(IHostingEnvironment hostingEnvironment, IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
this.extensionsPath = hostingEnvironment.ContentRootPath + this.Configuration["Extensions:Path"];
this._hostingEnvironment = hostingEnvironment;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment _hostingEnvironment;
private string extensionsPath;
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RazorViewEngineOptions>(options => {
options.ViewLocationExpanders.Add(new ViewLocationExpander(_hostingEnvironment));
});
services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
services.AddTransient<IBusinessServiceLocator, BusinessServiceLocator>();
services.AddTransient<IBusinessApiCalls, BusinessApiCalls>();
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddTransient<IUserService, UserService>();
services.AddAuthorization(o =>
{
o.AddPolicy("policyforcontrollers", b =>
{
b.RequireAuthenticatedUser();
});
});
services.RegisterDataTables();
services.AddMemoryCache();
services.AddSession(opt =>
{
opt.Cookie.IsEssential = true;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/usr/login";
options.LogoutPath = "/usr/logout";
});
services.AddExtCore(this.extensionsPath);
services.AddMvc(options =>
{
options.Conventions.Add(new AuthorizeControllerModelConvention());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseExtCore();
}
Вот мои помощники сеанса
public static class SessionExtensions
{
public static void SetJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetJson<T>(this ISession session, string key)
{
var sessionData = session.GetString(key);
return sessionData == null ? default(T) : JsonConvert.DeserializeObject<T>(sessionData);
}
}
public class SessionObject
{
public static string User { get; } = "USER";
}
В пользовательском контроллере я устанавливаю сеанс
await LoginAsync(user);
HttpContext.Session.SetJson(SessionObject.User, user);
, а в представлении я получаю доступ к объекту сеанса как
@{
ViewBag.Title = "Home";
Layout = "_Layout";
var session = Context.Session.GetJson<LoggedInUser>(SessionObject.User);
}
Объект сеанса в представлении имеет значение Null, и я заметил, чтоИдентификатор сеанса от usercontroller и идентификатор объекта сеанса в представлении отличается.Я не могу найти причину, почему это больше не работает.Чего мне не хватает?