【问题标题】:Event when response has been sent发送响应时的事件
【发布时间】:2012-12-10 22:16:06
【问题描述】:

我有一个控制器类,它继承自 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;
}

【问题讨论】:

  • 不能在动作结束时触发它吗?还是您允许他们直接访问生成的文件?
  • 不,该操作返回我假设的响应然后由基类异步发送到客户端。

标签: c# asp.net-mvc-4 asp.net-web-api


【解决方案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;
}

【讨论】:

  • 我实现了一个解决方案,使用 Stream 子类在处理流时删除文件。但是,我也得到了一个与 EndRequest 事件一起使用的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 2020-01-11
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多