Why I'm getting Unable to cast object of type 'Microsoft.AspNetCore.Mvc.ViewResult' to type 'Microsoft.AspNetCore.Mvc.ContentResult'?

3.7k Views Asked by At

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?

1

There are 1 best solutions below

3
Peter B On

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:

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
    if (filterContext.Result is ContentResult cr) // ADDED: type check using pattern matching
    {
        using (FileStream fs = new FileStream("c:\\logs\\log.txt", FileMode.Append))
        {
            using (StreamWriter sw = new StreamWriter(fs))
            {
                sw.WriteLine("Résultat: " + cr.Content);
            }
        }
    }
}