title: How to check Session and Validate the request in .Net Core Web API
body: <p>I am creating a .Net Core web API V3 project and in that project, I have a requirement:</p>
  <p>On every request check the SESSION, if it is ACTIVE then proceed else STOP the request and throw BAD REQUEST error.</p>
  <p>Now In my application, I have a SESSION table in my database and in that table I have a few columns among which I have</p>
  <p>Active (bit),</p>
  <p>Last Activity (Datetime(2)),</p>
  <p>Ended (Datetime(2)) column</p>
  <p>What I need:</p>
  <p>1- I need to update LastActivity column on every REQUEST on API.</p>
  <p>2- And in that context, we should validate that we have already set the session timeout value to 2 minutes in appSettings.json so then on every request we should first validate that if the time from LastActivity and current DateTime minutes is not greater then 2 minutes, if it is, then throws BadRequest error and stop the execution, else let it go and update the LastActivity column to current DateTime.</p>
  <p>What I Have Already Done (And is not working)</p>
  <pre><code>using System;
  using System.Linq;
  using DataAccess.Dtos;
  using DataAccess.Models;
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.AspNetCore.Mvc.Filters;
  using Microsoft.Extensions.Configuration;
  using Service.Contracts;
  
  namespace Motorlogs.API.Shared
  {
      public class SessionActionFilter : IActionFilter
      {
          public void OnActionExecuting(ActionExecutingContext context)
          {
              ISessionService _ISessionService = null;
              IConfiguration _IConfiguration = null;
  
              if (LoggedInUser.SessionId != null)
              {
                  Session session = _ISessionService.GetSessions(x =&gt; x.SID == LoggedInUser.SessionId).FirstOrDefault();
  
                  if (session != null)
                  {
                      if (session.Active == false)
                      {
                          context.Result = new BadRequestObjectResult(&quot;Session Expired! Please login again.&quot;);
                          return;
                      }
  
                      if (!session.LastActivity.HasValue)
                      {
                          session.LastActivity = DateTime.Now;
                          _ISessionService.UpdateSession(session);
                      }
                      else
                      {
                          var lastActivityTime = session.LastActivity;
                          var currentTime = DateTime.Now;
                          var requestDuration = currentTime.Subtract((DateTime)lastActivityTime);
                          var sessionTimeOutMinutes = TimeSpan.FromMinutes(int.Parse(_IConfiguration.GetSection(&quot;AppSettings:SessionExpiryTime&quot;).Value)).Minutes;
  
                          if (requestDuration.Minutes &gt;= sessionTimeOutMinutes)
                          {
                              session.Ended = DateTime.Now;
                              session.Active = false;
                              _ISessionService.UpdateSession(session);
                              context.Result = new BadRequestObjectResult(&quot;Session Expired! Please login again.&quot;);
                              return;
                          }
                          else
                          {
                              session.LastActivity = DateTime.Now;
                              _ISessionService.UpdateSession(session);
                          }
                      }
                  }
              }
          }
  
          public void OnActionExecuted(ActionExecutedContext context)
          {
              // our code after action executes
          }
      }
  }
  </code></pre>
  <p>And in Startup.cs</p>
  <pre><code>        public IServiceProvider ConfigureServices(IServiceCollection services)
          {
  
              services.AddDbContext&lt;MotorlogsContext&gt;(x =&gt;
                  x.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;)));
  
              services.AddMvc(option =&gt; option.EnableEndpointRouting = false)
                  //.AddNewtonsoftJson(options =&gt;
                  //    options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects)
                  .AddNewtonsoftJson(options =&gt;
                      options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
  
              services.AddCors(c =&gt;
              {
                  c.AddPolicy(&quot;AllowOrigin&quot;, options =&gt; options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
              });
  
              services.AddAuthentication(options =&gt;
                  {
                      options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                      options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                  })
                  .AddJwtBearer(options =&gt;
                  {
                      options.TokenValidationParameters = new TokenValidationParameters
                      {
                          ValidateIssuerSigningKey = true,
                          IssuerSigningKey = new SymmetricSecurityKey(
                              Encoding.ASCII.GetBytes(
                                  Configuration.GetSection(&quot;AppSettings:Token&quot;).Value)),
                          ValidateIssuer = false,
                          ValidateAudience = false
                      };
                  });
  
              services.AddDistributedMemoryCache();
  
              services.AddSession(options =&gt;
              {
                  options.IdleTimeout =
                      TimeSpan.FromMinutes(int.Parse(Configuration.GetSection(&quot;AppSettings:SessionExpiryTime&quot;)
                          .Value));
              });
  
              var identitySettingsSection = Configuration.GetSection(&quot;EmailConfiguration&quot;);
              services.Configure&lt;EmailConfiguration&gt;(identitySettingsSection);
              services.AddAutoMapper(typeof(Startup));
  
              services.AddSignalR(hubOptions =&gt;
              {
                  hubOptions.EnableDetailedErrors = true;
                  hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(1);
              });
  
              services.AddHttpContextAccessor();
  
              services.AddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;();
              services.AddSignalR();
              services.AddHostedService&lt;NotificationsHostedService&gt;();
  
              // This is the line I added for my SessionActionFilter
              services.AddScoped&lt;SessionActionFilter&gt;();
  
              return ConfigureIoC(services);
          }
  </code></pre>
  <p>Article I referred:</p>
  <p><a href="https://code-maze.com/action-filters-aspnetcore/" rel="nofollow noreferrer">https://code-maze.com/action-filters-aspnetcore/</a></p>
  <p>Thanks.</p>