在Web API asp.net核心中的OnActionExecuted中修改ActionExecutedContext的结果

时间:2019-01-16 07:49:15

标签: asp.net-core-webapi asp.net-core-2.1 custom-action-filter onactionexecuted

我正在custom filter中编写Web API,并且我想在ActionExecutedContext方法内修改OnActionExecuted的结果。

OkObjectResult返回action method时,结果类型为IActionResult

public void OnActionExecuted(ActionExecutedContext context)
{        
    var myResult = context.Result; 
    //Type of myResult is OkObjectResult          
}

因此,在这里如何将OkObjectResult转换为模型Object,以便可以使用properties并操纵值。

赞赏任何建议。

1 个答案:

答案 0 :(得分:1)

OkObjectResult的“ Value”属性返回Object。您可以修改对象的属性,甚至可以用新属性替换它。希望这对您有用。如果是这样,请将其标记为答案。

示例代码

public class Student
{
  public string Name { get; set; }
}

 [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet, Route("api/Test/GetString")]
        [SampleActionFilter]
        public ActionResult<Student> GetString(string name)
        {
            if(name.StartsWith("s"))
            {
                return Ok(new Student{ Name = $"This is data {name}" });
            }
            else
            {
                return Ok(new Student { Name = $"No Name" });
            }
        }
    }

 public class SampleActionFilterAttribute : TypeFilterAttribute
    {
        public SampleActionFilterAttribute() : 
        base(typeof(SampleActionFilterImpl))
        {
        }

    private class SampleActionFilterImpl : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {

            // perform some business logic work

        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            // perform some business logic work
            var myResult = (OkObjectResult)context.Result;

            //Add type checking here... sample code only
            //Modiy object values
            try
            {
                Student myVal = (Student)myResult.Value;
                myVal.Name = "Johnny";
            }
            catch { }
        }
    }
}