Reputation: 585
My controller action method returns pdf file as
public FileContentResult GetPDF(string filename)
{FileContentResult filecontent= new FileContentResult(Contents, "application/pdf");
HttpContext.Response.AddHeader("Content-Disposition", "inline; filename=" + filename);
return filecontent;
}
Now, it is not opening in a browser tab , so i want to return to url as filename.pdf at end that is how i can open pdf in browser tab.So how can i add that to my existing action method.
thanks,
michaeld
Upvotes: 1
Views: 1578
Reputation: 39491
Changing the browser url from server and at the same time downloading file content is impossible. Browser expects results to be received from the url it makes request to, so you cannot change it after you serve the file. So you have to have the handler for the url ending with ".pdf", and make the browser request files from that url, already ending with ".pdf". With asp.net mvc, that is simple. In your route configuration, you should now have something similar to
routes.MapRoute("PdfFile",
"DownloadFile/GetPDF/{fileName}",
new { controller = "DownloadFile", action = "GetPDF" });
And now, change the route to match only when url ends with ".pdf"
routes.MapRoute("PdfFile",
"DownloadFile/GetPDF/{fileName}.pdf",
new { controller = "DownloadFile", action = "GetPDF" });
//note the ending .pdf at the end of the route
And if you have designed your system to generate links authomatically using ActionLink
or other helpers, and not have written links by hand, you should already get the desired result - your links that download file now would automatically be generated to end with .pdf.
There's some technique in http when browser(or generally who makes the request) can be told that the resource it requests has been moved to some other url. That is supported by asp.net mvc too, by returning RedirectToAction
or similar actionResults. When the browser receives redirect response, it makes another request to that new url. In your case, this could have been used to redirect browser to url ending with ".pdf". But the key point here is that even in case of redirection of course you have to handle that url ending with ".pdf" :). So its better to get rid of those redirections and initially generate links that already point to desired url, by means changing the route configuration.
Upvotes: 2