有趣的小挑戰。
下面的代碼:
StreamWatcher.cs
public class StreamWatcher : Stream
{
private Stream _base;
private MemoryStream _memoryStream = new MemoryStream();
public StreamWatcher(Stream stream)
{
_base = stream;
}
public override void Flush()
{
_base.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _base.Read(buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
_memoryStream.Write(buffer, offset, count);
_base.Write(buffer, offset, count);
}
public override string ToString()
{
return Encoding.UTF8.GetString(_memoryStream.ToArray());
}
#region Rest of the overrides
public override bool CanRead
{
get { throw new NotImplementedException(); }
}
public override bool CanSeek
{
get { throw new NotImplementedException(); }
}
public override bool CanWrite
{
get { throw new NotImplementedException(); }
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
TitleModule.cs
public class TitleModule : IHttpModule
{
public void Dispose()
{
}
private static Regex regex = new Regex(@"(?<=<title>)[\w\s\r\n]*?(?=</title)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private StreamWatcher _watcher;
public void Init(HttpApplication context)
{
context.BeginRequest += (o, e) =>
{
_watcher = new StreamWatcher(context.Response.Filter);
context.Response.Filter = _watcher;
};
context.EndRequest += (o, e) =>
{
string value = _watcher.ToString();
Trace.WriteLine(regex.Match(value).Value.Trim());
};
}
}
你是什麼意思「提取任何字符串在標籤中」?您是否試圖操縱回覆給請求者的回覆?目前尚不清楚你想要做什麼。 – NerdFury 2009-09-04 17:32:01
對不起,我忘記了我的HTML標籤不會顯示出來,除非我把它放在一個代碼塊中。我不需要操縱響應,只需在標題標籤內提取字符串即可。 – spilliton 2009-09-04 17:53:40
要澄清,您是否試圖從響應中獲取內容或嘗試從內容中解析標記? – 2009-09-04 18:01:20