首页 > 解决方案 > 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"); 发生错误

任何人都可以帮忙吗?

标签: c#asp.net-core.net-core

解决方案


'尚未为此应用程序或请求配置会话。'"

通常,当您访问HttpContext.Session对象但之前从未注册过Session中间件时,会发生此错误。

确保.UseSession()被调用:

    公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env)
    {
        ...
        应用程序.UseSession();
        ...

        app.UseMvc(路由 =>
        {
            路线.MapRoute(
                名称:“默认”,
                模板:“{controller=Home}/{action=Index}/{id?}”);
        });
     }

另外,请注意在UseSession()使用之前必须调用HttpContext.Session. 至少,确保它在之前被调用过UseMvc()


推荐阅读