Unable to Create Session and Cookies in .NET Core

lesponce 176 Reputation points
2023-07-18T17:34:53.1233333+00:00

I've been trying to create a session or a cookie to be determine if the incoming parameter passed to call a hook is successfully received. The session is created and accessed when the code is running in the Startup.cs class. Once I try to retrieve the session from another page, the value is null.

In regards to the cookie, it doesn't get created in the startup.cs class.

Please review my code below. Any feedback is greatly appreciated.

using System;
using System.IO;
using System.Web;
using System.Text;
using Microsoft.AspNetCore.Http;


//using System.Web.HttpContext.Current.Session;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSession();
builder.Services.AddDistributedMemoryCache();


builder.Services.AddSession(options => 
{
    // Configure session options
    options.Cookie.Name = "YourSessionCookieName";
    options.IdleTimeout = TimeSpan.FromMinutes(20);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();




// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseSession();


app.MapPost("/webhook", async context =>
{
    var requestBody = await context.Request.ReadFromJsonAsync<WebhookPayload>();
    Console.WriteLine($"Header: {requestBody?.Header}, Body: {requestBody?.Body}");
    context.Response.StatusCode = 200;

    // Create a new Session
    context.Session.SetString("YourSessionKey", "YourSessionValue");
    var value = context.Session.GetString("YourSessionKey");

    // Create a new cookie
    var cookieOptions = new CookieOptions
    {
        // Set the cookie properties
        Path = "/",
        Expires = DateTime.UtcNow.AddDays(7),
        Secure = true, // Use "false" if not using HTTPS
        HttpOnly = true,
        SameSite = (Microsoft.AspNetCore.Http.SameSiteMode)SameSiteMode.Strict
    };

    context.Response.Cookies.Append("myKey", "myValue", cookieOptions);

    await context.Response.WriteAsync(requestBody.ToString());


});



app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();


public record WebhookPayload (string Header, string Body);





/* */
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,171 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,012 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,948 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
279 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 29,791 Reputation points Microsoft Vendor
    2023-07-19T03:01:43.03+00:00

    Hi @lesponce

    I do see the cookie in Postman. I don't see it in my browser's developer tool. How do see the cookie value or how do I retrieve it from another page?

    From the previous discussion, we know that to access the session value in the second request or another page, when send the request we need to add the session cookie in the request header, after that we can access the session value.

    In your scenario, before accessing another page via browser, I think you didn't call the webhook page, right? Because it is Post request. So, you can't see it in the browser's developer tools and then can't get the session value.

    To solve this problem, you can try to change the code, to access the webhook page using the MapGet() method, then we can directly access it via browser. Or if you still want to use the MapPost method, you have to create another web page (Get) and send a post request to webhook endpoint.

    app.MapGet("/webhook", async context =>
    {
        var requestBody = new WebhookPayload(context.Request.Query["Header"].ToString(), context.Request.Query["Body"].ToString()); 
    
        //var requestBody = await context.Request.ReadFromJsonAsync<WebhookPayload>();
        Console.WriteLine($"Header: {requestBody?.Header}, Body: {requestBody?.Body}");
        context.Response.StatusCode = 200;
    
        // Create a new Session
        context.Session.SetString("YourSessionKey", "YourSessionValue");
        var value = context.Session.GetString("YourSessionKey");
    
        // Create a new cookie
        var cookieOptions = new CookieOptions
        {
            // Set the cookie properties
            Path = "/",
            Expires = DateTime.UtcNow.AddDays(7),
            Secure = true, // Use "false" if not using HTTPS
            HttpOnly = true,
            SameSite = (Microsoft.AspNetCore.Http.SameSiteMode)SameSiteMode.Strict
        };
    
        context.Response.Cookies.Append("myKey", "myValue", cookieOptions);
    
        await context.Response.WriteAsync(requestBody.ToString());
    
    
    });
    

    Then, before access another page, you should access the webhook page first.

    The result as below: we can see that, after access the webhook page, the cookie was added to current domain, then when send the next request (to access another page), the session cookie will add to the request header, and we can access the session value.

    image2


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 52,576 Reputation points
    2023-07-18T18:27:01.0233333+00:00

    session is middleware. it adds a cookie with session id to any response, when the request does not send a session id. if sliding window is enabled, half-way to expiration the cookie is updated with a new expiration time.

    if you use postman or other tool to call /webhook, the response should have two cookie values. the session and your custom key.