会话”在Asp.net核心中引发了“ System.InvalidOperationException”类型的异常

时间:2019-11-07 10:41:52

标签: asp.net-core

我使用asp.net core v3构建了Web应用程序,因此我在启动文件中将idleTimeout设置为1分钟,但是1分钟后(测试空闲系统情况),我在上下文中遇到了以下异常

Session ='(((Microsoft.AspNetCore.Http.DefaultHttpContext)context).Session'引发了'System.InvalidOperationException'类型的异常

即使1分钟后,我也获得了context.User.Identity.IsAuthenticated的真值

所以当系统空闲1分钟时我需要帮助,因为我的前端是用react js构建的,所以它应该返回419作为返回码

namespace MyProject
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddSession(options =>
            {
                options.Cookie.Name = "AspNetSession";
                options.IdleTimeout = TimeSpan.FromMinutes(1);//TimeSpan.FromSeconds(20);
                options.IOTimeout = TimeSpan.FromMinutes(1);//TimeSpan.FromSeconds(20);
                options.Cookie.Path = "/";
                options.Cookie.HttpOnly = false;
                options.Cookie.IsEssential = true;

                //options.Cookie.Expiration = TimeSpan.FromMinutes(19);
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseAuthentication();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            app.UseHsts(option => option.MaxAge(days: 365).IncludeSubdomains());
            app.UseXXssProtection(option => option.EnabledWithBlockMode());
            app.UseXContentTypeOptions();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();


            app.Use((context, next) =>
            {


               //?ReturnUrl =% 2Fapi % 2FAccount % 2FGetUsersSession
               context.Response.OnStarting(() =>
               {
                  var result= context.User.Identity.IsAuthenticated;


                   if (context.Request.Query.Count>0)
                   {
                      // context.Response.StatusCode = 419;
                       var url = context.Request.Query.Keys.Contains("ReturnUrl");
                       if (url)
                       {
                           context.Response.StatusCode = 419;
                           // context.Response.
                           //context.Res
                           /// context.Response.WriteAsync("<html><label></label></html>");

                       }
                   }
                   else
                   {

                   }


                   string path = context.Request.Path.Value;
                   if (string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
                       string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase) ||
                       (path.Contains("/api")))
                   {


                        var tokens = antiforgery.GetAndStoreTokens(context);


                       context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken,
                          new CookieOptions() { HttpOnly = false, Secure=true }) ;
                   }


                   if (!context.Response.Headers.Keys.Contains("X-Frame-Options"))
                   {
                       context.Response.Headers.Add("X-Frame-Options", "DENY");
                   }

                   context.Response.Headers.Remove("Server");
                   context.Response.Headers.Remove("X-Powered-By");
                   context.Response.Headers.Remove("X-SourceFiles");
                   return Task.CompletedTask;
               });
               return next();
           });
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",

                    template: "{controller}/{action}/{id?}");

                routes.MapRoute(
                    name: "default",

                    template: "{controller}/{action}/{id?}");


            });
            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {

                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

0 个答案:

没有答案