2017-06-12 244 views
2

我的要求:編寫一箇中間件,用於過濾來自其他後續中間件(例如Mvc)的響應中的所有「壞詞」。修改中間件響應

問題:響應的流式傳輸。所以當我們回到我們的FilterBadWordsMiddleware從一個後來的中間件,已經寫到響應,我們太晚了黨...因爲響應開始已經發送,這產生了衆所周知的錯誤response has already started ...

因此,這是許多不同情況下的一項要求 - 如何處理?

回答

4

將響應流替換爲MemoryStream以防止發送。響應被修改後返回原始流:

public class EditResponseMiddleware 
{ 
    private readonly RequestDelegate _next; 

    public EditResponseMiddleware(RequestDelegate next) 
    { 
     _next = next; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     var originBody = context.Response.Body; 

     var newBody = new MemoryStream(); 

     context.Response.Body = newBody; 

     await _next(context); 

     newBody.Seek(0, SeekOrigin.Begin); 

     string json = new StreamReader(newBody).ReadToEnd(); 

     context.Response.Body = originBody; 

     await context.Response.WriteAsync(modifiedJson); 
    } 
} 

這是一種解決方法,它可能會導致性能問題。我希望在這裏看到更好的解決方案。

+0

This Works,thanks!我發現在某些情況下,將回調附加到'context.Response.OnStarting()'也可以,但在修改響應時不起作用。另外我不喜歡使用'OnStarting()',因爲它打破了迭代中間件工作流程。 – Matthias