在ActionFilterAttribute中解析ResultExecutedContext

时间:2014-04-24 22:15:45

标签: c# asp.net-mvc-4

在我的控制器中,JsonResult方法如下所示:

public JsonResult MyTestJsonB()
{
    return Json(new {Name = "John", Age = "18", DateOfBirth = DateTime.UtcNow}, "text/plain", JsonRequestBehavior.AllowGet);
}

在我的以下OnResultExecuted属性类方法....

    public class JsonResultAttribute : ActionFilterAttribute
    {

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
....
        }
    }

我希望能够解析filterContext,如下所示。我如何完成以下工作?

  1. 我希望能够检测到结果是System.Web.MVC.JsonResult类型。

  2. 在结果中,我希望能够深入了解数据属性

  3. 使用Property,我希望能够检测传入的对象是否具有DateTime类型的属性。例如,如果对象如下:{Name =“John”,Age =“18”,DateOfBirth = {4/24/2014 7:05:58 PM}},我希望能够检测到该属性DateOfBirth是日期时间类型。

  4. 如果它有DateTime,那么我想采取某些行动。

1 个答案:

答案 0 :(得分:0)

您可以使用System.Reflection

来实现此目的
public class JsonResultAttribute : ActionFilterAttribute
{

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {

        // Detect that the result is of type JsonResult
        if (filterContext.Result is JsonResult)
        {
            var jsonResult = filterContext.Result as JsonResult;

            // Dig into the Data Property
            foreach(var prop in jsonResult.Value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var propName = prop.Name;
                var propValue = prop.GetValue(jsonResult.Value,null);

                Console.WriteLine("Property: {0}, Value: {1}",propName,     propValue);

                // Detect if property is an DateTime
                if (propValue is DateTime)
                {
                    // Take some action
                }
            }
        }
    }
}

不要忘记在行动中添加[JsonResultAttribute]

相关问题