简体   繁体   中英

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

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:

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);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM