Saqib
Saqib

Reputation: 2283

Passing parameters from middleware to controller - asp.net core

I need to pass some parameters from middleware to controller and I'm confused which approach should I use if I have to take care of performance, resource usage and security.

(It is the requirement to keep the Session enabled anyway.)

Upvotes: 3

Views: 2600

Answers (2)

Marcus Höglund
Marcus Höglund

Reputation: 16846

You could pass it as an http header down the pipeline with the request

public class UserHeaderMiddleware  
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        context.Request.Headers.Add("user-id", new[] { userId.ToString() });
        await _next(context);
    }
}

Upvotes: 3

eltiare
eltiare

Reputation: 1939

If you need to store the user ID for the future, session is the way to go. Items only passes it along for that request.

Upvotes: 1

Related Questions