Jagankumar
Jagankumar

Reputation: 121

Can you add a cookie to request with asp.net core middleware?

Am trying to write custom middleware in the ASP.net core pipeline, as part of my invoke, would like to append/add cookie, so then next middleware in the pipeline can access those cookie.

getting compiling error on set the cookie value. Can anyone recommend work around for this.

Note: When I tried with Response.Cookie , it works but only problem is, cookie is reflecting only on next request from the browser, but I need this to be reflecting on the next middleware in the pipeline immediately after execute this.

below code snippet

  public async Task Invoke(HttpContext httpContext)
        {


            var queryParameters = httpContext.Request.Query;
            var cookies = httpContext.Request.Cookies;
            if (!cookies.ContainsKey(".AspNetCore.Session")
                || cookies[".AspNetCore.Session"] != "new_key")
            {

httpContext.Request.Cookies[".AspNetCore.Session"] = "new_key";

            }


            await _next.Invoke(httpContext);
        }

Upvotes: 6

Views: 10974

Answers (2)

demoncodemonkey
demoncodemonkey

Reputation: 11957

In my case I have an AuthorizationHandler that performs some checks to determine the user details and whether the user is logged in. The auth handler stores some of this info in a token in the request headers, so it can be easily accessed by the controllers.

When the user is logged in, this token can be read from the HttpContext.Request.Headers in a standard controller and all is well.

When the user is not logged in, the auth handler returns failure and so the request is redirected to "/login". Sadly the token header is not preserved across the redirect, so in my LoginController the token is null.

The only way I could make the token available to both a standard controller and LoginController is to store the token in both the request headers AND response cookies. This cookie can be read from the LoginController in the HttpContext.Request.Cookies collection. I set it to be short-lived as it's only needed briefly (it'll disappear after 5 seconds)

Here is part of the code from my auth handler:

  HttpRequest request = _httpContextAccessor.HttpContext.Request;
  HttpResponse response = _httpContextAccessor.HttpContext.Response;

  request.Headers["X-Token"] = encryptedToken;
  response.Cookies.Append("TokenCookie", encryptedToken, new CookieOptions
    {
        MaxAge = TimeSpan.FromSeconds(5),
        Secure = true,
        IsEssential = true,
    });

Upvotes: 0

Win
Win

Reputation: 62300

You cannot use cookie's value in same request. However, you could use good old HttpContext.Items.

public async Task InvokeAsync(HttpContext context)
{
    context.Request.HttpContext.Items["key"] = "Hello!";
    await _next(context);
}

You then retrieve it as

var value = HttpContext.Items["key"];

Upvotes: 5

Related Questions