How can I get user and claim information using action filters?

前端 未结 2 752
轻奢々
轻奢々 2020-12-23 12:19

Right now I am doing this to get the information I need:

In my base controller:

    public int roleId { get; private set; }
    public int userId { g         


        
2条回答
  •  北海茫月
    2020-12-23 12:46

    Create a custom ActionFilter class (for OnActionExecuting):

    using System.Security.Claims;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    
    namespace YourNameSpace
    {
        public class CustomActionFilterAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                ClaimsIdentity claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
                filterContext.ActionParameters["roleId"] = int.Parse(claimsIdentity.FindFirst("RoleId").Value);
                filterContext.ActionParameters["userId"] = int.Parse(claimsIdentity.GetUserId());
            }    
        }
    }
    

    Then decorate a choice of Base Controller, Controller or Action(s) (depending on the level you want to apply the custom filter), and specify roleId and userId as Action parameters:

    [CustomActionFilter]
    public async Task getTest(int roleId, int userId, int examId, int userTestId, int retrieve)
    {
        // roleId and userId available to use here
        // Your code here
    }
    

    Hopefully that should do it.

提交回复
热议问题