忙着写一些遗留代码写入csv / xls:
// Set up response
string filename = "ErrorControlExport";
string attachment = "attachment; filename=" + filename + "_" + DateTime.UtcNow.ToFileTime() + "." + extension;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Pragma", "public");
// Clear any settings (such as GZip)
HttpContext.Current.Response.Filter = null;//exception occurs here
// Add BOM to force recognition of UTF-8
byte[] bom = new byte[] { 0xef, 0xbb, 0xbf };
HttpContext.Current.Response.BinaryWrite(bom);
但是当代码到达时:
// Clear any settings (such as GZip)
HttpContext.Current.Response.Filter = null;//exception occurs here
它会抛出HttpException
响应过滤器无效。
所以我的问题是:
1)如何将过滤器设置为空过滤器或默认过滤器?
2)是否有必要?
提前感谢您的帮助
答案 0 :(得分:9)
检查此post。即使它谈论ASp.Net 3.5,我尝试了它,它的工作原理。我刚刚阅读过滤器var filter = Response.Filter
,然后为其分配了空Response.Filter = null
答案 1 :(得分:1)
除了@ Nileshs'评论/答案(我使用此方法时为+1)
另一种选择是创建一个空过滤器:
/// <summary>
/// Creates and empty filter for HttpResponse.Filter (i.e no proessing is done on the text before writting to the stream)
/// </summary>
class EmptyFilter : MemoryStream
{
private string source = string.Empty;
private readonly Stream filter;
public EmptyFilter(HttpResponse httpResponseBase)
{
this.filter = httpResponseBase.Filter;
}
public override void Write(byte[] buffer, int offset, int count)
{
this.source = Encoding.UTF8.GetString(buffer);
this.filter.Write(Encoding.UTF8.GetBytes(this.source), offset, Encoding.UTF8.GetByteCount(this.source));
}
}
而不是简单地设置为:
HttpContext.Current.Response.Filter = new EmptyFilter(HttpContext.Current.Response);
答案 2 :(得分:0)
尝试清理您的解决方案并删除旧的DLL(可能是从项目重命名中遗留下来的)。那为我排序了。