Json的HTTP模块流问题
我有,我用它来清理我的web服务返回的JSON的HTTP模块(见http://www.codeproject.com/KB/webservices/ASPNET_JSONP.aspx?msg=3400287#xx3400287xx对于这样的一个例子。)基本上它涉及从javascript调用跨域JSON Web服务。Json的HTTP模块流问题
有这个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);
}
感谢您的帮助! 贾斯汀
它的方法多次触发的原因是因为它会缓冲的内容,然后将其发送到输出流。这里是一个例子,展示了如何创建ViewState移动器HttpModule。你可以从实现中得到一些想法。向下滚动到底部并查看结果。
http://www.highoncoding.com/Articles/464_Filtering_Responses_Using_ASP_NET_Response_Filters.aspx
另一种解决方案是写在ResponseStream Flush方法。就像在this的例子。
我修改JsonHttpModules Flush方法和使用的StringBuilder存储在像贾斯汀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);
}
这样你就不必猜测输入流的结束了。
谢谢,那篇文章给了我我需要的东西! public override void Write(byte [] buffer,int offset,int count) string json = System.Text.Encoding.UTF8.GetString(buffer,offset,count); (json); var endOfFile = new Regex(“]”); if(endOfFile.IsMatch(json)) {message} = _context.Request.Params [“callback”] +“(”+ _sb.ToString()+“);”; buffer = System.Text.Encoding.UTF8.GetBytes(message); _responseStream.Write(buffer,0,buffer.Length); } } – Justin 2010-03-12 05:06:55
太棒了!很高兴我能帮上忙! – azamsharp 2010-03-12 05:16:54