I gave your filter a spin and (after corrections) it produces a nasty COM error.
This is because the async nature of the the operation: OnResultExecuted
is your last chance to do something but this happens when the response (with the filename but not the file itself) has been send back to the client. When the client (browser) then starts the download a Not Found error or worse is produced.
In other words, your approach looks nice but it won't work.
Some rough ideas for a solution:
- make sure your server side files have unique names and a reliable timestamp
- use a background process to periodically clean them up, or
- clean up old file every time you prepare a new one
I changed your filter like this:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
var r = filterContext.Result as FilePathResult; // not FileContent
string fileName =
filterContext.RequestContext.HttpContext.Server.MapPath(r.FileName);
System.IO.File.Delete(fileName);
}
Update :
Thanks to this SO answer, the following should work:
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
var r = filterContext.Result as FilePathResult; // not FileContent
string fileName =
filterContext.RequestContext.HttpContext.Server.MapPath(r.FileName);
filterContext.HttpContext.Response.Flush();
filterContext.HttpContext.Response.End();
System.IO.File.Delete(fileName);
}