0

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.
}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

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.