asp.net-core-webapiasp.net-core-2.1custom-action-filteronactionexecuted

Modifying the result from ActionExecutedContext inside OnActionExecuted in web api asp.net core


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.


Solution

  • 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 { }
            }
        }
    }