SoFunction
Updated on 2025-03-01

c# Method of using Session in WebAPI

Recently, when rewriting WebApp, I changed the Captcha that I wrote in generic processing routines to use WebApi to implement the mechanism. During the implementation process, I found that using IRequiresSessionState session cannot be used (==null)

After checking some articles, I found that I need to register the API route and rewrite the RouteHandler before I can use it. The following uses MVC 4 to explain the part to be implemented

Create HttpControllerHandler and HttpControllerRouteHandler and overwrite it

  public class SessionRouteHandler : HttpControllerHandler, IRequiresSessionState
  {
    public SessionRouteHandler(RouteData routeData) : base(routeData)
    {

    }
  }

  public class SessionControllerRouteHandler : HttpControllerRouteHandler
  {
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {

      return new SessionRouteHandler();

    }

  }

Change to

(using ) and specify RouteHandler

public static void Register(HttpConfiguration config)
{
  (

  name: "DefaultApi",

  routeTemplate: "api/{controller}/{id}",

  defaults: new { id =  }

  ).RouteHandler=new SessionControllerRouteHandler();
}

Or Session session support is not enabled by default in MVC WebApi. Need to override the Init method in Global to specify the type that the session needs to support

public override void Init()
    {
      PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
      ();
    }

    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
      (
        );
    }

or:

    public override void Init()
    {
       += (sender, e) => ();
      ();
    }

It is not enabled by default. SessionStateBehavior has four values:

  • Default uses default logic to determine the requested session state behavior. The default logic is to find out if there is a tagged session state interface in the IHttpHandler.
  • Disabled does not enable session state to handle requests. This setting overrides any session behavior that has been determined by the handler for checking the request.
  • ReadOnly enables read-only session state for requests. This means that the session status cannot be updated. This setting overrides any session state behavior that has been determined by the check requested handler.
  • Required enables full read-write session state behavior for requests. This setting overrides any session behavior that has been determined by the handler for checking the request.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.