Get the current user, within an ApiController action, without passing the userID as a parameter

前端 未结 8 1396
时光说笑
时光说笑 2020-12-02 09:50

How do we get the current user, within an secure ApiController action, without passing the userName or userId as a parameter?

We assume that this is available, beca

8条回答
  •  情书的邮戳
    2020-12-02 09:58

    string userName;
    string userId;
    if (HttpContext.Current != null && HttpContext.Current.User != null 
            && HttpContext.Current.User.Identity.Name != null)
    {
        userName = HttpContext.Current.User.Identity.Name;
        userId = HttpContext.Current.User.Identity.GetUserId();
    }
    

    Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.

    // get httpContext
    object httpContext;
    actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);    
    

    See also:

    How to access HTTPContext from within your Web API action

提交回复
热议问题