1

I am writing custom filter in my Web API and there I want to modify the result of ActionExecutedContext inside the OnActionExecuted method.

I got the result type as OkObjectResult as the action method is returning IActionResult.

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

So here how can I convert this OkObjectResult to my model Object, So that I can use the properties and manipulate the values.

Appreciated any suggestion.

Tufan Chand
  • 692
  • 4
  • 19
  • 36

1 Answers1

4

The OkObjectResult's "Value" property returns the Object. You can modify the Object's properties or even replace it with a new one. Hope this works for you. If it does, please mark this as answer.

Sample CODE:

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 { }
        }
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Phantom2018
  • 514
  • 1
  • 3
  • 8
  • Not able to assign OkObjectResult's Value property, it's available only the time of debugging. – Tufan Chand Jan 16 '19 at 10:23
  • Provided tested sample code. You can adapt to your scenario. (I have implemented an ActionFilter and applied it to a "GetString" method on the controller.) (In the sample code, the "Name" value will always be "Johnny" (as set in the OnActionExecuted method). – Phantom2018 Jan 16 '19 at 10:41