简体   繁体   中英

How to flush response in ActionFilter of asp.net core?

I am trying to delete a file that is dynamically generated at my controller using an ActionFilter.

public class DeleteFileAttribute : ActionFilterAttribute {
    public override void OnActionExecuted(ActionExecutedContext context) {
        /* MVC 4 code which worked just fine
        context.HttpContext.Response.Flush();

        var filePathResult = context.Result as FilePathResult;

        if(filePathResult!=null){
            File.Delete(filePathResult.FileName);
        }
        End of MVC 4 code */

        // I am not able to flush response as context.HttpContext.Response does not have a Flush method
        var vb = (context.Controller as Controller).ViewBag;
        string fileToDelete = vb.FileToDelete;

        if(File.Exists(fileToDelete)) {
            // ERROR: Process cannot access the file ... because it is being used by another process
            File.Delete(fileToDelete);
        }
    }
}

As mentioned in the code comment, since I am not able to flush the response and then delete the file I get IOException: The process cannot access the file ... because it is being used by another process exception.

What is a sure way to delete the file in the action filter after the user has finished downloading it?

Using OnResultExecuted event instead of OnActionExecuted in the action filter solved the issue. No flushing of Response is needed.

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