3

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.

  • context.Items["user-id"] = "12345";
  • context.Session.SetInt32("user-id", 12345);

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

0

2 Answers 2

3

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);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

apparently it would be the third option to do that but it's not what I'm asking.
@MuhammadSaqib yeah, sorry. Missed that you said you needed to stick with the session. I leave this answer here as it still has a point, IMO
Ya you have provided a third way to do that which can also be helpful for future visitors. Session is available already I don't need to stuck with it. I have two (now three) choices to transfer parameters to controllers and I have to pick best one.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.