博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NetCore MVC 静态文件生成
阅读量:6835 次
发布时间:2019-06-26

本文共 5805 字,大约阅读时间需要 19 分钟。

hot3.png

using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Mvc.Infrastructure;using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Options;using System;using System.Collections.Generic;using System.IO;using System.Text;namespace NetCore.MVC{    ///     /// 访问静态页面过滤器    ///     [System.AttributeUsage(AttributeTargets.Method)]    public class StaticHtmlAttribute:ActionFilterAttribute    {        ///         /// 静态路由配置        ///         /// 静态路由地址        /// 数据id名称        public StaticHtmlAttribute(string url,string idfield="id")        {            Url = url;            idField = idfield;        }        ///         /// 静态文件路由        ///         public string Url { get; set; }        ///         /// 参数标识        ///         public string idField { get; set; }        ///         /// 是否清除文件标识        ///         private string RemoveClearKey = "remove";         ///         /// 静态文件根目录        ///         private string StaticFilesRootName        {            get            {                return ApplicationEnvironments.Site.BaseDirectory  + "html/";            }        }        public override void OnActionExecuting(ActionExecutingContext context)        {            string id = context.RouteData.Values.ContainsKey(idField) ? context.RouteData.Values[idField].ToString() : "";            if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(idField))            {                id = context.HttpContext.Request.Query[idField];            }            string filePath = StaticFilesRootName + string.Format(Url, id);            //判断文件是否存在            if (File.Exists(filePath))            {                if ( context.HttpContext.Request.Query.ContainsKey(RemoveClearKey))                {                    RemoveClearKey = context.HttpContext.Request.Query[RemoveClearKey];                    if (!string.IsNullOrWhiteSpace(RemoveClearKey))                    {                        File.Delete(filePath);                    }                }                else                {                    //如果存在,直接读取文件                    using (FileStream fs = File.Open(filePath, FileMode.Open))                    {                        using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))                        {                            //通过contentresult返回文件内容                            ContentResult contentresult = new ContentResult();                            contentresult.Content = sr.ReadToEnd();                            contentresult.ContentType = "text/html";                            context.Result = contentresult;                        }                    }                }            }            base.OnActionExecuting(context);        }        public override void OnActionExecuted(ActionExecutedContext context)        {            CreateHtml(context);            base.OnActionExecuted(context);        }        ///         /// 生成html方法        ///         private void CreateHtml(ActionExecutedContext context)        {            IActionResult actionResult = context.Result;            if (actionResult is ViewResult)            {                ViewResult viewResult = actionResult as ViewResult;                //下面的代码就是执行这个ViewResult,并把结果的html内容放到一个StringBuiler对象中                var services = context.HttpContext.RequestServices;                var option = services.GetRequiredService
>(); var executor = services.GetRequiredService
>() as ViewResultExecutor ?? throw new ArgumentNullException("executor"); var result = executor.FindView(context, viewResult); result.EnsureSuccessful(originalLocations: null); var view = result.View; StringBuilder builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var viewContext = new ViewContext( context, view, viewResult.ViewData, viewResult.TempData, writer, option.Value.HtmlHelperOptions); view.RenderAsync(viewContext).GetAwaiter().GetResult(); //这句一定要调用,否则内容就会是空的 writer.Flush(); } //按照规则生成静态文件名称 string id = context.RouteData.Values.ContainsKey(idField) ? context.RouteData.Values[idField].ToString() : ""; if (string.IsNullOrEmpty(id) && context.HttpContext.Request.Query.ContainsKey(idField)) { id = context.HttpContext.Request.Query[idField]; } string filePath = StaticFilesRootName + string.Format(Url, id); FileInfo info = new FileInfo(filePath); if (!info.Exists) { if (!info.Directory.Exists) { info.Directory.Create(); } } //写入文件 using (FileStream fs = File.Open(filePath, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { sw.Write(builder.ToString()); } } //输出当前的结果 ContentResult contentresult = new ContentResult(); contentresult.Content = builder.ToString(); contentresult.ContentType = "text/html"; context.Result = contentresult; } } }}

 

转载于:https://my.oschina.net/u/3049482/blog/3019339

你可能感兴趣的文章
转发:Hekaton:SQL Server集成的内存事务处理
查看>>
[转]孙鑫VC教程例子代码1---Windows程序内部运行原理
查看>>
手把手玩转win8开发系列课程(11)
查看>>
在可编辑div中插入文字或图片的问题解决思路
查看>>
发现问题,是解决问题的第一步
查看>>
c#中在规定时间弹出窗体
查看>>
win7高级搜索
查看>>
Asp.net Ajax框架教程
查看>>
C#Winform控件随窗体缩放
查看>>
JS常用代码收集
查看>>
Windows 如何在cmd命令行中查看、修改、删除与添加环境变量
查看>>
[转]新版.Net开发必备十大工具
查看>>
VC:键盘钩子函数
查看>>
englis translate,word
查看>>
ConText
查看>>
java异常捕获
查看>>
Android Service的绑定 基础概念篇
查看>>
MVC项目开发中那些用到的知识点(登录权限认证)
查看>>
错误总结
查看>>
Delphi7 (第一天:类的编写)续
查看>>