Home > Enterprise >  Pass data to controller method from AuthorizationFilter in ASP.Net Core Web API
Pass data to controller method from AuthorizationFilter in ASP.Net Core Web API

Time:12-20

I have implemented a custom AuthorizationFilter in my ASP.NET Core Web API. The filter checks for a code in the request header and identifies the userID based on the code.

I want this userID to be reused in my GET/POST call. How can I transfer data from my AuthorizationFilter to my calling method to avoid duplicate database calls?

AuthorizationFilter function:

public void OnAuthorization(AuthorizationFilterContext context)
{
        string header = _httpContextAccessor.HttpContext.Request.Headers["CODE"].ToString();

        int userID = GetAccessData(header);
        //Want to use this UserID in my calling method
}

Calling function in my controller:

[HttpGet]
public IActionResult UseData(Model modelObj)
{
     // I want to use userID retrieved at filter level here.
}

CodePudding user response:

transfer data from my AuthorizationFilter to my calling method

Below is a work demo, I use two options, you can refer to it.

CustomAuthenticationFilter :

public class CustomAuthenticationFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {  
             //you can use your userID
             //Option 1
            context.HttpContext.Items["userID"] = "1111111";
           
             //Option 2
             var userId = "22222";
             context.RouteData.Values.Add("UserId", userId);
        }
    }

Action:

        [HttpGet]
        [CustomAuthenticationFilter]
        public IActionResult UseData()
        {
            
            // I want to use userID retrieved at filter level here.
            var userID = HttpContext.Items["userID"];
            var userid2 = RouteData.Values["UserId"];
            return Ok(userID);
        }

result:

enter image description here

  • Related