Background and Requirements
The project uses the MVC4 framework, which has a feature to generate PDF files based on the settings and preview them directly when clicked.
Implementation process
1, the first version of the implementation code:
HTML content
@{Layout = null;} <! DOCTYPE html>
Controller code
Public ActionResult getpdf () { return new Filepathresult ("~/content/the garbage Collection handbook.pdf", " Application/pdf "); }
Cons: Title and file download when the name is not very friendly.
1, the second version of the implementation code:
We have done 2 things:
1. Allow download popup to display friendly download file name.
2, let the other two in the browser display getpdf also display friendly content.
Custom Actionfilter, modify the header to become inline. (Direct so replace do not know whether there is a hidden danger.) )
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); } } }
Custom Actionnameselector implements the interception and judgment of the action name.
public class Myactionnameselecter:actionnameselectorattribute {public override bool IsValidName (ControllerContext ControllerContext, String actionname, MethodInfo MethodInfo) { return actionname.contains ("-pdf file Preview");}}
The code in the controller is modified as follows
[Myactionnameselecter] [Mypdfactionfilter] public ActionResult getpdf () { return new Filepathresult ("~/content/the Garbage Collection Handbook.pdf "," application/pdf ") //Add Filedownloadname settings, but this will allow the content to respond to the browser in the form of an attachment (specific reference file response mode: inline and attachment). //file becomes downloaded by the browser. {filedownloadname = "the Garbage Collection Handbook.pdf"};}
The page content is modified as follows
@{Layout = null;} <! DOCTYPE html>
Final effect