简体   繁体   English

如何在asp.net核心的ActionFilter中刷新响应?

[英]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. 我试图删除一个使用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. 正如代码注释中所提到的,因为我无法刷新响应然后删除文件我得到IOException: The process cannot access the file ... because it is being used by another process异常使用。

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. 在操作过滤器中使用OnResultExecuted事件而不是OnActionExecuted解决了该问题。 No flushing of Response is needed. 不需要刷新响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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