c# - System.Private.CoreLib.dll 中发生“System.InvalidOperationException”,但未在用户代码中处理
问题描述
我正在使用依赖注入通过类(组件)访问我的应用程序会话中的信息,但是在访问时最终会给出错误:“System.Private 中发生'System.InvalidOperationException'类型的异常。 CoreLib.dll 但未在用户代码中处理:“尚未为此应用程序或请求配置会话。”
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
//Adiciona uma implementação padrão na memória do IDistributedCache.
services.AddDistributedMemoryCache();
//Session
services.AddSession(options =>
{
//Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.Cookie.HttpOnly = true;
//Make the session cookie essential
options.Cookie.IsEssential = true;
});
services.AddHttpContextAccessor();
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;
});
//Adicionar os filtros nos controllers
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
//adicionado por instância
options.Filters.Add(new CustomActionFilter());
options.Filters.Add(new CustomAsyncActionFilter());
//adicionado por tipo
options.Filters.Add(typeof(CustomActionFilter));
options.Filters.Add(typeof(CustomAsyncActionFilter));
});
//Injeção de Dependência
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<Common.AtualizarFiltros.IRefreshPF, Common.AtualizarFiltros.RefreshPF>();
}
我的控制器.cs
public class PessoaFisicaController : Controller
{
private readonly IRefreshPF _refreshPF;
public PessoaFisicaController(IRefreshPF refreshPF)
{
_refreshPF = refreshPF;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async void AddOrRemoveSexo([FromBody] Models.Json.JsonJsonAddOrRemoveSexo jsonInput)
{
await _refreshPF.AddOrRemoveSexoAsync(jsonInput);
}
}
我的类.cs
public interface IRefreshPF
{
Task AddOrRemoveSexoAsync(Models.Json.JsonJsonAddOrRemoveSexo jsonInput);
}
public class RefreshPF : IRefreshPF
{
private readonly IHttpContextAccessor _context;
public RefreshPF(IHttpContextAccessor context)
{
_context = context;
}
public async Task AddOrRemoveSexoAsync(Models.Json.JsonJsonAddOrRemoveSexo jsonInput)
{
int idSexo = 0;
//Modelos
Model.SqlServer.Segmentacao.Sexo sexo = new Model.SqlServer.Segmentacao.Sexo();
Models.Session.SessionResumoContagem sessionResumoContagem = new Models.Session.SessionResumoContagem();
string[] array = jsonInput.id.Split('_');
idSexo = int.Parse(array[1]);
sexo = await Service.Filtros.GetByIdSexoAsync(idSexo);
sessionResumoContagem = _context.HttpContext.Session.Get<Models.Session.SessionResumoContagem>("ResumoContagem");
if (sessionResumoContagem == null)
{
sessionResumoContagem = new Models.Session.SessionResumoContagem();
sessionResumoContagem.tipoPessoa = (int)Model.Enumeradores.TipoPessoa.PessoaFisica;
_context.HttpContext.Session.Set<Models.Session.SessionResumoContagem>("ResumoContagem", sessionResumoContagem);
}
if (sessionResumoContagem.sexos == null)
{
sessionResumoContagem.sexos = new List<Model.SqlServer.Segmentacao.Sexo>();
}
}
}
sessionResumoContagem = _context.HttpContext.Session.Get("ResumoContagem"); 发生错误
任何人都可以帮忙吗?
解决方案
'尚未为此应用程序或请求配置会话。'"
通常,当您访问HttpContext.Session
对象但之前从未注册过Session
中间件时,会发生此错误。
确保.UseSession()
被调用:
公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env) { ... 应用程序.UseSession(); ... app.UseMvc(路由 => { 路线.MapRoute( 名称:“默认”, 模板:“{controller=Home}/{action=Index}/{id?}”); }); }
另外,请注意在UseSession()
使用之前必须调用HttpContext.Session
. 至少,确保它在之前被调用过UseMvc()
。
推荐阅读
- c - 如何按升序按位值打印数字的每个数字
- powerbi - 字典中不存在给定的键 - PowerBI
- icons - 我已从 FontAwesome 4 升级到 font awesome 5,unicode 图标未在服务器中呈现
- cakephp - 如何在 cakePHP4 中禁用授权中间件?
- java - 如何在 Spring Boot 应用程序中杀死内螺纹
- javascript - 地图与异步/等待不同步
- javascript - _ga cookie 在不处于隐身模式时不会被清除/过期 - 使用 Javascript
- php - 如何设置 SOAP 请求以在 php 中使用 SoapClient?
- python - 如何将样式转移 tensorflow 模型转换为具有灵活输入形状的 mlmodel?
- java - Java SSL 套接字在现有套接字 SSLSocketFactory 上分层:它需要主机参数吗?