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>
  • 相关阅读:
    MVC3、如何应用EntityFramework 连接MySql 数据库 Kevin
    DEV EXPRESS Summary Footer 不显示 Kevin
    装饰模式 Kevin
    Dev 控件 GridControl 控件 二次绑定数据源的问题。 Kevin
    System.InvalidOperationException 异常 Kevin
    LINQ to XML Kevin
    代理模式——代码版“吊丝的故事” Kevin
    VS2012 中的设备 面板 Kevin
    maven 学习笔记(三)创建一个较复杂的 eclipse+android+maven 工程
    maven 学习笔记(一)eclipse+android+maven
  • 原文地址:https://www.cnblogs.com/zhuji/p/11309145.html
Copyright © 2011-2022 走看看