我有一个HTTP模块用于清理我的Web服务返回的JSON(请参阅http://www.codeproject.com/KB/webservices/ASPNET_JSONP.aspx?msg=3400287#xx3400287xx以获取此示例。)基本上它与从javascript调用跨域JSON Web服务有关。 / p>
有这个JsonHttpModule使用JsonResponseFilter Stream类来写出JSON,重载的Write方法应该围绕JSON包装回调函数的名称,否则JSON会因需要标签而出错。但是,如果JSON非常长,则会多次调用Stream类中的Write方法,从而导致回调函数错误地插入到JSON的中途。在Stream类中是否有一种方法可以在最后围绕流包装回调函数,或者指定它在1个Write方法中而不是在块中写入所有JSON?
这里是JsonHttpModule中调用JsonResponseFilter的地方:
public void OnReleaseRequestState(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
if (!_Apply(app.Context.Request)) return;
// apply response filter to conform to JSONP
app.Context.Response.Filter =
new JsonResponseFilter(app.Context.Response.Filter, app.Context);
}
这是JsonResponseFilter Stream类中多次调用的Write方法:
public override void Write(byte[] buffer, int offset, int count)
{
var b1 = Encoding.UTF8.GetBytes(_context.Request.Params["callback"] + "(");
_responseStream.Write(b1, 0, b1.Length);
_responseStream.Write(buffer, offset, count);
var b2 = Encoding.UTF8.GetBytes(");");
_responseStream.Write(b2, 0, b2.Length);
}
感谢您的帮助! 贾斯汀
答案 0 :(得分:0)
多次触发该方法的原因是它将缓冲内容然后将其发送到输出流。这是一个示例,显示如何创建ViewState移动器HttpModule。您可以从实施中获得一些想法。向下滚动到底部并查看结果。
http://www.highoncoding.com/Articles/464_Filtering_Responses_Using_ASP_NET_Response_Filters.aspx
答案 1 :(得分:0)
另一个解决方案是在Flush方法中编写ResponseStream。就像在this示例中一样。
我修改了JsonHttpModules Flush方法,并使用StringBuilder在Justin等Write方法中存储流。
/// <summary>
/// Override flush by writing out the cached stream data
/// </summary>
public override void Flush()
{
if (_sb.Length > 0)
{
string message = _context.Request.Params["callback"] + "(" + _sb.ToString() + ");";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
_responseStream.Write(buffer, 0, buffer.Length);
}
// default flush behavior
_responseStream.Flush();
}
public override void Write(byte[] buffer, int offset, int count)
{
string json = System.Text.Encoding.UTF8.GetString(buffer, offset, count);
_sb.Append(json);
}
这样您就不必尝试猜测传入流的结束。