zoukankan      html  css  js  c++  java
  • MVC自定定义扩展点之ActionNameSelectorAttribute+ActionFilterAttribute 在浏览器中打开pdf文档

    仅仅演示 了ASP.MVC 5 下为了在在浏览器中打开pdf文档的实现方式之一,借此理解下自定义ActionNameSelectorAttribute+ActionFilterAttribute 类的作用

    在浏览器中发生请求 http://localhost:51878/Home/通过指南 ASP.NET MVC response 保存在 Content/通关指南-中文0410.pdf ,效果是在浏览器中直接显示该pdf

    分别实现 MyActionNameSelecter MyPdfActionFilter

     MyActionNameSelecter.cs

    namespace MVC5.Demo.Controllers
    {
        public class MyActionNameSelecter : ActionNameSelectorAttribute
        {
            public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
            {
                return actionName.Contains("通关指南");
            }
        }
    }

    MyPdfActionFilter.cs

    namespace MVC5.Demo.Controllers
    {
        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);
                }
            }
        }
    }

    HomeController

    [MyActionNameSelecter]
    [MyPdfActionFilter] 
    public ActionResult GetPdf() { //return new FilePathResult("~/content/The Garbage Collection Handbook.pdf", "application/pdf"); //增加FileDownloadName设置,但是这会让内容以附件的形式响应到浏览器(具体参考文件响应模式:内联和附件)。 //文件变成被浏览器下载。 return new FilePathResult("~/content/通关指南-中文0410.pdf", "application/pdf") { FileDownloadName = "Guide Handbook.pdf" }; }

     其它

    xxx.cshtml

    <div>
        @* 第二个参数可能是一个动态生成的内容,需要ACTION中增加名称选择拦截,所以自定义了一个ActionNameSelectorAttribute类(即MyActionNameSelecter)满足要求。 *@
        @Html.ActionLink("预览PDF", "通关指南", null, new { target = "_blank" })
    </div>
  • 相关阅读:
    世界黑客怎么排名?曝郭盛华公司30万美元收购海外域名,怎么回事
    AI应该享有与动物一样的权利吗?
    2020年将会迎来人工智能新浪潮,哪些商业巨头已经提前布局好了?
    揭秘郭盛华的真实收入,事实和你想的真不一样
    Excel表格中单击一个单元格如何将整行整列变色
    ldconfig与 /etc/ld.so.conf
    在excel中,应用公式到多行
    Excel怎么把两个单元格中的文字合并到一个单元格中
    在EXCEL中批量添加超链接
    windows中对文件进行排序
  • 原文地址:https://www.cnblogs.com/zhuji/p/11309145.html
Copyright © 2011-2022 走看看