I'm following this tutorial on Linkedin Tutorial , and in this video the presenter shows how to use ActionFilter , however , when I execute this application
Unable to cast object of type 'Microsoft.AspNetCore.Mvc.ViewResult' to type 'Microsoft.AspNetCore.Mvc.ContentResult'
ProductActionFilter
public override void OnResultExecuted(ResultExecutedContext filterContext) { var result = (ContentResult)filterContext.Result; // Exception thrown here using (FileStream fs = new FileStream("c:\\logs\\log.txt", FileMode.Append)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine("Résultat: " + result.Content); } } }
What is the reason of this?
It's quite possible that the ActionFilter executes multiple times, and sometimes it may execute for situations that differ from what you are anticipating.
Try doing a check for the expected type, then only proceed if the type is found, which can be done as follows: