Can OWIN middleware use the http session?

Yes, but it's quite a hack. It also won't work with SignalR because SignalR MUST run before session is acquired to prevent long session locks.

Do this to enable session for any request:

public static class AspNetSessionExtensions
{
    public static IAppBuilder RequireAspNetSession(this IAppBuilder app)
    {
        app.Use((context, next) =>
        {
            // Depending on the handler the request gets mapped to, session might not be enabled. Force it on.
            HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
            return next();
        });
        // SetSessionStateBehavior must be called before AcquireState
        app.UseStageMarker(PipelineStage.MapHandler);
        return app;
    }
}

Then you can access the session with either HttpContext.Current.Session or

HttpContextBase httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

This answer is a remix from the initial answer, so the gist of it should be attributed to @Tratcher. It's different enough though to post it seperately instead of suggesting an edit.


Supposing you want to make a small OWIN app for basic testing purposes (e.g. as a stub/fake for a bigger API when doing integration tests), including a slightly hakish way of using session state would work just fine.

First up, you need these:

using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Owin;

With those you can create a helper method:

public static void RequireAspNetSession(IAppBuilder app)
{
    app.Use((context, next) =>
    {
        var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
        httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
        return next();
    });

    // To make sure the above `Use` is in the correct position:
    app.UseStageMarker(PipelineStage.MapHandler);
}

You could also create that as an extension method as the original answer did.

Note that if you don't use the UseStageMarker you would encounter this error:

Server Error in '/' Application. 'HttpContext.SetSessionStateBehavior' can only be invoked before 'HttpApplication.AcquireRequestState' event is raised.

In any case, with the above you can now use HttpContext in your OWIN app like this:

public void Configuration(IAppBuilder app)
{
    RequireAspNetSession(app);

    app.Run(async context =>
    {
        if (context.Request.Uri.AbsolutePath.EndsWith("write"))
        {
            HttpContext.Current.Session["data"] = DateTime.Now.ToString();
            await context.Response.WriteAsync("Wrote to session state!");
        }
        else
        {
            var data = (HttpContext.Current.Session["data"] ?? "No data in session state yet.").ToString();
            await context.Response.WriteAsync(data);
        }
    });
}

If you fire up IIS Express with this little app you'll first get:

No data in session state yet.

Then if you go to http://localhost:12345/write you'll get:

Wrote to session state!

Then if you go back / go to any other url on that host you'll get:

11/4/2015 10:28:22 AM

Or something similar.


Comments

  1. Aryan

    • 2020/9/12

    , but it's quite a hack. It also won't work with SignalR because SignalR MUST run before session is acquired to prevent long session locks.

  2. Aarav

    • 2015/8/4

    31. Yes, but it's quite a hack. It also won't work with SignalR because SignalR MUST run before session is acquired to prevent long session locks. Do this to enable session for any request: public static class AspNetSessionExtensions{ public static IAppBuilder RequireAspNetSession(this IAppBuilder app) { app.Use((context, next) => { // Depending on the handler the request gets mapped to, session might not be enabled.

  3. Joel

    • 2016/5/4

    I had a little bit of code that I was duplicating for ASP.NET and SignalR and I decided to rewrite it as OWIN middleware to remove this duplication.

  4. Raul

    • 2015/8/9

    From a controller, you could use HttpContext.Current.GetOwinContext().GetSessionContext() to get the context. If you're using this inside an ApiController, consider using the OwinSessionMiddleware.WebApi package which has some convenient extension methods you can use inside your controller actions:

  5. Kelly

    • 2015/6/25

    Can OWIN middleware use an http session? I had some code that I duplicated for ASP.NET and SignalR, and I decided to rewrite it as OWIN middleware

  6. Emerson

    • 2015/2/22

    Although OWIN middleware components (OMCs) are primarily designed to run in a server-agnostic pipeline, it is possible to run an OMC in the IIS integrated pipeline as well ( classic mode is not supported ). An OMC can be made to work in the IIS integrated pipeline by installing the following package from the Package Manager Console (PMC): Console.

  7. Clayton

    • 2018/6/8

    To be able to use session in OWIN, the following code should be placed in Startup.cs before any middleware is registered. Otherwise, HttpContext.Current.

  8. Titus

    • 2019/12/8

    Each application can add multiple middlewares to form an OWIN middleware pipeline for request processing similar to HttpModules in classic Asp.Net applications. The middleware components runs in the same order it is added in the Startup class.

  9. Sean

    • 2017/12/8

    A session is a way to store information (properties) to be used across multiple requests. While it does use a cookie for remembering the session id inside the 

  10. Boone

    • 2017/2/17

    Use, Run, and Map. Configure the HTTP pipeline using Use, Run, and Map. The Use method can short-circuit the pipeline (that is, if it doesn't call a next request delegate). Run is a convention, and some middleware components may expose Run[Middleware] methods that run at the end of the pipeline.

  11. Bianco

    • 2021/7/2

    In essence, OWIN suggests a way of building software modules (called middlewares) that can process HTTP requests and responses.

  12. Maximus

    • 2020/2/23

    Therefore, OWIN proposes the usage of middlewares (pieces of software that can intercept and modify HTTP requests and responses) rather than defining a processing chain/pipeline for them.

  13. Lucas

    • 2016/7/3

    Use method. That is, the OWIN pipeline in the Katana runtime will process OMCs in the order they were registered using IAppBuilder.Use . In the 

  14. Mauricio

    • 2019/5/22

    Each middleware component gets a reference to the next step in the OWIN pipeline. Since AppFunc returns a Task it means we can await the next step, effectively performing processing on the way in and the way out (request / response). To wire up middleware we call IAppBuilder.Use(object middleware).

  15. Kelvin

    • 2015/12/13

    Can perform work before and after the next component in the pipeline. If the app uses session state, call Session Middleware after 

  16. Amir

    • 2020/8/8

    Session был null, и я не видел никакого объекта сеанса на IOwinContext Можно ли получить доступ к сеансу http из OWIN? Extensions; using Owin;.

  17. Kyler

    • 2020/11/14

    OpenID Connect OWIN middleware leverages that mechanism to minimize the configuration request and the HTTP mechanism that should be used to carry them.

Comments are closed.

Recent Posts