MarsS
MarsS

Reputation: 111

Get the user ID inside a custom middleware

I'm creating a middleware that based on a cookie makes an operation ... But for that I need the id of the logged user.

Is this possible in InvokeAsync?

Upvotes: 1

Views: 3925

Answers (2)

Rosco
Rosco

Reputation: 2474

Custom middleware has the InvokeAsync method which has a HttpContext parameter.

HttpContext has a User property which gives information on the current user context.

public async Task InvokeAsync(HttpContext context)
{
    var userIdentity = context.User.Identity;
    var uName = userIdentity.Name;
    // ...

Upvotes: 1

Nan Yu
Nan Yu

Reputation: 27538

You can try below code sample :

app.Use(async (context, next) =>
{
    var userIdentity = context.User.Claims.Where(x=>x.Type==ClaimTypes.NameIdentifier).FirstOrDefault().Value;
    // Do work that doesn't write to the Response.
    await next.Invoke();
    // Do logging or other work that doesn't write to the Response.
});

Upvotes: 0

Related Questions