杜淳的父亲是谁,魔女西西,天下女人心259
背景及需求
项目使用的是mvc4框架,其中有一个功能是根据设置生成pdf文件,并在点击时直接预览。
实现过程
1、第一版实现代码:
html内容
@{ layout = null; } <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>index</title> </head> <body> <div> @html.actionlink("预览pdf","getpdf",null,new { target="_blank"}) </div> </body> </html>
控制器代码
public actionresult getpdf() { return new filepathresult("~/content/the garbage collection handbook.pdf", "application/pdf"); }
缺点:标题和文件下载时名称不是很友好。
1、第二版实现代码:
我们做了2件事情:
1、让下载弹出框能显示友好的下载文件名。
2、让浏览器中的其他两个显示getpdf的地方也显示友好的内容。
自定义actionfilter,对header进行修改,变为内联。(直接这么替换不知道会不会有隐患。)
public class mypdfactionfilter : actionfilterattribute { public override void onresultexecuted(resultexecutedcontext filtercontext) { //content-disposition=attachment%3b+filename%3d%22the+garbage+collection+handbook.pdf%22} var filerheader = filtercontext.httpcontext.response.headers.get("content-disposition"); if (!string.isnullorempty(filerheader) && filerheader.substring(0, "attachment".length).tolower().equals("attachment")) { filtercontext.httpcontext.response.headers["content-disposition"] = "inline" + filerheader.substring("attachment".length, filerheader.length - "attachment".length); } } }
自定义actionnameselector实现对action名称的拦截和判断。
public class myactionnameselecter : actionnameselectorattribute { public override bool isvalidname(controllercontext controllercontext, string actionname, methodinfo methodinfo) { return actionname.contains("-pdf文件预览"); } }
控制器内代码修改如下
[myactionnameselecter] [mypdfactionfilter] public actionresult getpdf() { return new filepathresult("~/content/the garbage collection handbook.pdf", "application/pdf") //增加filedownloadname设置,但是这会让内容以附件的形式响应到浏览器(具体参考文件响应模式:内联和附件)。 //文件变成被浏览器下载。 { filedownloadname = "the garbage collection handbook.pdf" }; }
页面内容修改如下
@{ layout = null; } <!doctype html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>index</title> </head> <body> <div> @* 第二个参数可能是一个动态生成的内容,需要action中增加名称选择拦截,所以自定义了一个actionnameselectorattribute类满足要求。 *@ @html.actionlink("预览pdf", "the garbage collection handbook-pdf文件预览", null,new { target="_blank"}) </div> </body> </html>
最终效果
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论