C# 正在分析ActionFilterAttribute中的ResultExecutedContext
在我的控制器中,JsonResult方法如下所示:C# 正在分析ActionFilterAttribute中的ResultExecutedContext,c#,asp.net-mvc-4,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 JsonResultAttrib
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。我如何做到以下几点
我希望能够检测到结果的类型是System.Web.MVC.JsonResult
在结果中,我希望能够深入研究数据属性
通过属性,我希望能够检测传入的对象是否具有DateTime类型的属性。例如,如果对象如下:{Name=John,Age=18,DateOfBirth={4/24/2014 7:05:58 PM}},我希望能够检测到属性DateOfBirth的类型是DateTime
如果它有DateTime,那么我想采取某些行动
您可以使用System.Reflection实现这一点: 不要忘记在操作中添加[JsonResultAttribute]
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
}
}
}
}
}