0

我想将数据库中的每个操作方法参数名称及其对应值记录为键值对。作为其中的一部分,我使用了 OnActionExecuting ActionFilterAttribute,因为它将是获取 Action Executing 上下文的正确位置(OnActionExecuting 方法将为所有控制器操作方法调用调用)。

我正在获取 .Net 类型(字符串、int、bool)的值。但我无法获得用户定义类型(自定义类型)的值。(例如:登录模型)。我的模型可能还有一些其他嵌套的用户定义类型。

我试图获取用户定义类型的值,但我得到了唯一的类名作为字符串。我希望我们能在反思中做到。

您能否请任何人协助解决问题。因为我是反思的新手。这对我会有帮助。提前致谢。我需要在 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);
}

用户定义类型

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

我能够在 OnActionExecuting 中获取 returnUrl(登录方法参数)的值,但不能获取模型(登录方法参数)的值。我能够看到这些值,但不知道如何访问它,即使我无法获得它,我也使用了 typeof,但我需要泛型,因为我在控制器中有 20 个方法,所以我不仅可以用于 LoginModel。

4

1 回答 1

1

这个答案并不完全是你想要的——根据你的问题——但我认为它对于想要完成的事情会更好。一边快速...

在这种情况下玩反射和嵌套类,对我来说会导致一些 SO(提议?)错误......

那么,也许是一条更好的道路?与其尝试从“context.ActionParameters”获取/转换属性名称、值(类型?),我发现让 Json 序列化为我完成工作要容易得多。然后你可以持久化 Json 对象,然后反序列化......非常容易。

无论如何,这是代码:

using Newtonsoft.Json; // <-- or some other serialization entity
//...
 public class LogActions : ActionFilterAttribute, IActionFilter
    {

        // Using the example -- LoginModel, UserRequestBase objects and Login controller...

        void IActionFilter.OnActionExecuting(ActionExecutingContext context)
        {
            var param = (Dictionary<String, Object>)context.ActionParameters;

            foreach (var item in param.Values)
            {
                string itemName = item.GetType().Name.ToString();
                string itemToJson = JsonConvert.SerializeObject(item);


                // Save JsonObject along with whatever other values you need (route, etc)
            }
        }

    }

然后,当您从数据库中检索 Json 对象时,您只需反序列化/强制转换它。

LoginModel model = (LoginModel)JsonConvert.DeserializeObject(itemToJson, typeof(LoginModel));

从示例:

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

示例中使用的控制器:

public ActionResult Login(LoginModel model, string returnUrl)
{
     return View(model);
}

希望这可以帮助。如果还有其他问题,请告诉我,我会尽力提供帮助。

于 2014-11-21T23:51:09.227 回答