如何在 asp.net 核心的 ActionFilter 中刷新响应?
How to flush response in ActionFilter of asp.net core?
我正在尝试删除在我的控制器上使用 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);
}
}
}
如代码注释中所述,由于我无法刷新响应然后删除文件,因此出现 IOException: The process cannot access the file ... because it is being used by another process
异常。
用户下载完成后删除操作过滤器中文件的可靠方法是什么?
在操作过滤器中使用 OnResultExecuted
事件而不是 OnActionExecuted
解决了这个问题。不需要刷新 Response。
我正在尝试删除在我的控制器上使用 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);
}
}
}
如代码注释中所述,由于我无法刷新响应然后删除文件,因此出现 IOException: The process cannot access the file ... because it is being used by another process
异常。
用户下载完成后删除操作过滤器中文件的可靠方法是什么?
在操作过滤器中使用 OnResultExecuted
事件而不是 OnActionExecuted
解决了这个问题。不需要刷新 Response。