1

我有一个控制器类,它继承ApiController并处理来自客户端的 HTTP 请求。

其中一个操作在服务器上生成一个文件,然后将其发送给客户端。

我试图弄清楚一旦响应完成后如何清理本地文件。

理想情况下,这将通过在向客户端发送响应后触发的事件来完成。

有这样的活动吗?或者我想要实现的目标是否有标准模式?

[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;
}
4

1 回答 1

1

查看OnResultExecuted事件 - 您可以向方法添加自定义过滤器并在那里处理事件。

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

Global.asax 中的EndRequest事件也可能是一个选项。

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

    EndRequest += MyEventHandler;
}
于 2012-12-10T14:16:06.433 回答