MVC静态化
//添加StaticFileWriteFilterAttribute public class StaticFileWriteFilterAttribute : FilterAttribute, IResultFilter { public void OnResultExecuted(ResultExecutedContext filterContext) { } public void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.HttpContext.Response.Filter = new StaticFileWriteResponseFilterWrapper(filterContext.HttpContext.Response.Filter, filterContext); } class StaticFileWriteResponseFilterWrapper : System.IO.Stream { private System.IO.Stream inner; private ControllerContext context; public StaticFileWriteResponseFilterWrapper(System.IO.Stream s, ControllerContext context) { this.inner = s; this.context = context; } public override bool CanRead { get { return inner.CanRead; } } public override bool CanSeek { get { return inner.CanSeek; } } public override bool CanWrite { get { return inner.CanWrite; } } public override void Flush() { inner.Flush(); } public override long Length { get { return inner.Length; } } public override long Position { get { return inner.Position; } set { inner.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { return inner.Read(buffer, offset, count); } public override long Seek(long offset, System.IO.SeekOrigin origin) { return inner.Seek(offset, origin); } public override void SetLength(long value) { inner.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { inner.Write(buffer, offset, count); try { string p = context.HttpContext.Server.MapPath(HttpContext.Current.Request.Path); if (Path.HasExtension(p)) { string dir = Path.GetDirectoryName(p); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (File.Exists(p)) { File.Delete(p); } File.AppendAllText(p, System.Text.Encoding.UTF8.GetString(buffer)); } } catch { } } } }
在Global.asax中的RegisterRoutes 添加路由
routes.MapRoute( "HTMLDefault", // Route name "Subject/Index/{ArticleId}_{PageIndex}.html", // URL with parameters new { controller = "Subject", action = "Index", ArticleId = 0, PageIndex=0 } // Parameter defaults );
在位于View层的web.config中添加Handler
<system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="BlockViewHandler"/> <add name="htmlHandler" verb="GET,HEAD" path="*.html" type="System.Web.StaticFileHandler"/> <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> </handlers> </system.webServer>
对需要静态化的Action上添加属性标签
[StaticFileWriteFilter] public ActionResult Index(int ArticleId,int pageIndex)