从ResultExecutedContext结果中获取值

时间:2018-02-27 16:40:21

标签: c# .net asp.net-core httpcontext

如何从ResultExecutedContext结果中获取值? 在调试中我可以看到有值: enter image description here

但是知识分子并没有看到它。

1 个答案:

答案 0 :(得分:0)

使用System.ReflectionJsonResult来获得您想要的值。还要将[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
                }
            }
        }
    }
}