2012-12-10 40 views
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; 
} 
+0

不能在行動結束時開火嗎?還是你讓他們直接訪問生成的文件? –

+0

不,這個動作返回我假設的Response然後被基類異步地發送給客戶端。 – Nick

回答

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; 
} 
+1

我使用Stream子類實現了一個解決方案,以便在處理流時刪除文件。不過,我也有一個解決'EndRequest'事件的解決方案。 – Nick