I want to log the each action method parameter name and its corresponding values in the database as key value pair. As part of this, I am using OnActionExecuting ActionFilterAttribute, since it will be the right place (OnActionExecuting method will get invoke for all controller action methods call) to get Action Executing context.
I am getting the value for .Net types (string, int, bool). But I am unable to get the value of the User defined types (custom types). (ex: Login model). My model might have some other nested user defined types as well.
I was trying to get the values of the user defined types but I am getting the only class name as string. I hope we can do in reflection.
Could you please anyone assist to resolve the issue. since I am new to reflection. It will helpful to me. Thanks in Advance. I need to get the name and value of these types in OnActionExecuting.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionParameter = new SerializableDictionary<string,string>();
if(filterContext.ActionParameter != null)
{
foreach(var paramter in filterContext.ActionParameter)
{
//able to get returnUrl value
//unable to get model values
ActionParameter.Add(paramter.Key, paramter.Value);
}
}
}
public ActionResult Login(LoginModel model, string returnUrl)
{
return View(model);
}
User defined type
public class LoginModel
{
public string UserName {get;set;}
public string Password {get;set;}
//User defined type
public UserRequestBase Request {get;set;}
}
//User defined type
public class UserRequestBase
{
public string ApplicationName {get;set;}
}
I am able to get the value of the returnUrl (login method param) in OnActionExecuting but not for model (login method param). I am able to see the values, but don't know how to access it, I used typeof even though I am unable to get it, but I need generic because i have 20 methods in controller so I could not only for LoginModel.
This answer isn't exactly what you want - based on your question - but I think it will work better for what want to accomplish. Quick aside...
Playing around with reflection and nested classes in this instance, lead to some SO (a propos?) errors for me...
So, a better path, maybe? Rather than trying to get/cast the property names, values (types?) from 'context.ActionParameters,` I found it was much easier to let a Json serialization do the work for me. You can then persist the Json object, then deserialize... pretty easy.
Anyway, here's the code:
Then when you retrieve the Json object from the database you just have to deserialize / cast it.
From example:
Controller used in example:
Hope this helps. If there are further issues with this please let me know and I will try to help.