1

I have a controller class which inherits from ApiController and handles HTTP requests from a client.

One of the actions generates a file on the server and then sends it to the client.

I'm trying to figure out how to clean up the local file once the response has been fulfilled.

Ideally this would be done through an event which fires once a response has been sent to the client.

Is there such an event? Or is there a standard pattern for what I'm trying to achieve?

[HttpGet]
public HttpResponseMessage GetArchive(Guid id, string outputTypes)
{
    //
    // Generate the local file
    //
    var zipPath = GenerateArchive( id, outputTypes );

    //
    // Send the file to the client using the response
    //
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(zipPath, FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    response.Content.Headers.ContentLength = new FileInfo(zipPath).Length;
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = Path.GetFileName(zipPath)
    };

    return response;
}
Nick
  • 25,026
  • 7
  • 51
  • 83
  • Can't just fire it at the end of the action? or are you allowing them direct access to the generated file? – Brad Christie Dec 10 '12 at 13:41
  • No, the action returns the Response which I'm assuming is then sent asynchronously to the client by the base class. – Nick Dec 10 '12 at 13:42

1 Answers1

1

Take a look at the OnResultExecuted event - you can add a custom filter to the method and handle the event there.

public class CustomActionFilterAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
         ///filterContext should contain the id you will need to clear up the file.
    }
}

The EndRequest event in Global.asax may also be an option.

public override void Init() {
    base.Init();

    EndRequest += MyEventHandler;
}
Community
  • 1
  • 1
Mark Jones
  • 12,156
  • 2
  • 50
  • 62
  • 1
    I implemented a solution using a Stream subclass to delete the file when the stream is disposed. However, I also got a solution working with the `EndRequest` event. – Nick Dec 11 '12 at 08:55