Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .NET Core Session in middleware

When I write middleware in .NET Core which short-circuits the chain and returns a response, it does not set the session cookie. A short example:

public class Middleware
{

    private RequestDelegate _next;

    public Middleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var req = context.Request;
        if (req.Path.ToString() == "/hello-world")
        {
            context.Response.StatusCode = 200;
            context.Response.Headers["Content-Type"] = "text/html; charset=utf-8";
            await context.Response.WriteAsync("Hello, world!");
            return;
        }

        await _next(context);

    }

}

Here is the relevant code from my Startup class:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddDistributedMemoryCache()
            .AddSession();
    }

    public void Configure(IApplicationBuilder app)
    {
        app
            .UseSession()
            .UseMiddleware<Middleware>();
    }
}

Response headers on pass-through:

HTTP 200 No Error

Server: Kestrel
Set-Cookie: .AspNetCore.Session=CfDJ8C1XpX5nCrFCnHz%2BDwlF41YjVSyPMqB8Qmk6qcDPnOSpG22yun3hsXpRBgMDhlX%2ByLbqkUtqPRYY%2B1%2Bno5WeRLnabM1zBDggvB4YEg6ooBiGN%2B5ktjjgfp4uH5mmlWZpEQyQJQb0vKDGwqWpMlLEGjMxVIMqOnkqjM0DvsQIPjt6; path=/; samesite=lax; httponly
Content-Type: text/html; charset=utf-8
Pragma: no-cache
Transfer-Encoding: Identity
Date: Thu, 18 Jan 2018 20:48:55 GMT
Expires: -1
Cache-Control: no-cache

Response headers on the short-circuit:

HTTP 200 No Error

Transfer-Encoding: Identity
Content-Type: text/html; charset=utf-8
Server: Kestrel
Date: Thu, 18 Jan 2018 21:17:39 GMT

In short, I need to know why the session middleware is not sending the cookie back. I also appear to get some session warnings when I load the page about not being able to decode the cookie.

like image 484
eltiare Avatar asked Jan 18 '18 21:01

eltiare


People also ask

Can we use session in .NET Core?

ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID. The cookie session ID: Is sent to the app with each request. Is used by the app to fetch the session data.

What is the use of middleware in .NET Core?

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.

How does session work in .NET Core?

Session is a feature in ASP.NET Core that enables us to save/store the user data. Session stores the data in the dictionary on the Server and SessionId is used as a key. The SessionId is stored on the client at cookie. The SessionId cookie is sent with every request.

Can we use session in API?

But in practice, yes - you may need to access a user's session from a web API. By default this is not possible. Attempting to call HttpContext. Current.


1 Answers

I hadn't added anything to the session so the middleware wasn't creating the session. Simply add context.Session.SetString("stuff", "3"); (or one of Set* variants) in order to have the session sent to the client. You'll want to do this before you write to the response body.

like image 124
eltiare Avatar answered Sep 25 '22 00:09

eltiare