Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MVC Action parameter from AuthorizationContext?

I am currently trying to write a custom authentication filter and I need to access the dto that is being passed as a parameter to the action in my filter. Lets say I have an action like this

[AuthenticateProfile]
public ActionResult EditProfile(ProfileDTO profileDto)
    {
        if (ModelState.IsValid)
        {
            // Do crazy stuff
        }

        return something....
    }

I need to do my authentication based on some of the properties that are inside profiledto object.

I want to know how I can get this object inside my filter from AuthorizationContext.

like image 827
Rob Schneider Avatar asked Sep 16 '25 10:09

Rob Schneider


2 Answers

Here's how I did it:

var parameters = filterContext.ActionDescriptor.GetParameters();
var values = parameters.Select(s => new 
             {
                 Name = s.ParameterName,
                 Value = filterContext.HttpContext.Request[s.ParameterName]
             });
like image 90
nullable Avatar answered Sep 18 '25 10:09

nullable


Assuming that your logic is happening in OnActionExecuting (meaning before the actual controller action is run), then one way of doing this (as outlined here) would be:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   if (!filterContext.Controller.ViewData.ModelState.IsValid)
      return;

   var profileDto = filterContext.ActionParameters.SingleOrDefault(ap => ap.Key == "profileDto").Value;
   if (profileDto != null)
   {
      // do something with profileDto
   }
}
like image 33
rossipedia Avatar answered Sep 18 '25 09:09

rossipedia