问题是,我无法控制Response.OutputStream,如果我能够这样做,我将简单地根据结果流计算ETag。
我在WCF中做了这个事情,但是在MVC中找不到任何简单的想法。
我想要写这样的东西
- [ETag]
- public ActionResult MyAction()
- {
- var myModel = Factory.CreateModel();
- return View(myModel);
- }
任何想法?
解决方法
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Web.Mvc;
- public class ETagAttribute : ActionFilterAttribute
- {
- private string GetToken(Stream stream) {
- MD5 md5 = MD5.Create();
- byte [] checksum = md5.ComputeHash(stream);
- return Convert.ToBase64String(checksum,checksum.Length);
- }
- public override void OnResultExecuted(ResultExecutedContext filterContext)
- {
- filterContext.HttpContext.Response.AppendHeader("ETag",GetToken(filterContext.HttpContext.Response.OutputStream));
- base.OnResultExecuted(filterContext);
- }
- }
这应该是有效的,但是不行。
显然,Microsoft overrode System.Web.HttpResponseStream.Read(Byte [] buffer,Int32 offset,Int32 count),以便它返回“Specified方法不受支持”,不知道为什么他们会这样做,因为它继承了System。 IO.Stream基类…
哪个是混合以下资源,Response.OutputStream是一个只写的流,所以我们必须使用一个Response.Filter类来读取输出流,一种古怪的,你必须在过滤器上使用一个过滤器,但是它的工作=)
http://bytes.com/topic/c-sharp/answers/494721-md5-encryption-question-communication-java
http://www.codeproject.com/KB/files/Calculating_MD5_Checksum.aspx
http://blog.gregbrant.com/post/Adding-Custom-HTTP-Headers-to-an-ASPNET-MVC-Response.aspx
http://www.infoq.com/articles/etags
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
更新
经过多次的战斗,我终于可以得到这个工作:
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Web;
- using System.Web.Mvc;
- public class ETagAttribute : ActionFilterAttribute {
- public override void OnActionExecuting(ActionExecutingContext filterContext) {
- try {
- filterContext.HttpContext.Response.Filter = new ETagFilter(filterContext.HttpContext.Response);
- } catch (System.Exception) {
- // Do Nothing
- };
- }
- }
- public class ETagFilter : MemoryStream {
- private HttpResponseBase o = null;
- private Stream filter = null;
- public ETagFilter (HttpResponseBase response) {
- o = response;
- filter = response.Filter;
- }
- private string GetToken(Stream stream) {
- byte[] checksum = new byte[0];
- checksum = MD5.Create().ComputeHash(stream);
- return Convert.ToBase64String(checksum,checksum.Length);
- }
- public override void Write(byte[] buffer,int offset,int count) {
- byte[] data = new byte[count];
- Buffer.BlockCopy(buffer,offset,data,count);
- filter.Write(data,count);
- o.AddHeader("ETag",GetToken(new MemoryStream(data)));
- }
- }
更多资源:
http://authors.aspalliance.com/aspxtreme/sys/Web/HttpResponseClassFilter.aspx
http://forums.asp.net/t/1380989.aspx/1