You can see the Physical file is directly show in Browser URL |
In ASP .NET and ASP .NET MVC for hiding the physical path PDF URL we use HTTP Handler ( .ashx) file but in .NET core the .ashx is not support. To achieve this We use a simple method to read the PDF content in byte format and through FileStreamResult and then append that PDF in browser.
Let's Create an example of .NET Core and check both how traditionally the physical path of PDF are show in URL and how to secure the link that the physical path are not show in browser URL.
Step-1:
New Project ==> Choose ASP .NET Core Web Application
Open "Index.cshtml" and add two anchor tag and crate the javascript function to call the action controller.
<script type="text/javascript">
function OpenPDFByPath() {
$.ajax({
method: 'GET',
url: '@Url.Action("OpenPDFPath", "Home")',
data: {}
}).done(function (data, statusText, xhdr) {
var URL = "../" + data;
window.open(URL, "", "width=700,height=600");
}).fail(function (xhdr, statusText, errorText) {
});
}
function OpenPDFHidingPath() {
window.open('@Url.Action("OpenPDF", "Home")', "", "width=700,height=600")
}
</script>
<div class="row">
<div class="col-md-6">
<h2>PDF Open with Physical Path</h2> <a href="#" onclick="OpenPDFByPath()">Click here to Open PDF</a>
</div>
<div class="col-md-6">
<h2>PDF Open with hiding Physical Path</h2> <a href="#" onclick="OpenPDFHidingPath()">Click here to Open PDF</a>
</div>
</div>
>> We create two anchor tag and call onclick() method each. >> Call action method each to open the Sample PDF. >> The dummy PDFs are in WWWroot ==> PDF's folder ==> Samplefile.PDFStep-3:
Open the HomeController.cs file and two action method. One is return the physical file through AJAX call method name is OpenPDFPath() that return the physical file directly.
public JsonResult OpenPDFPath()
{
string PDFpath = "PDFs/Samplefile.PDF";
return Json(PDFpath);
}
public FileResult OpenPDF()
{
string PDFpath = "wwwroot/PDFs/Samplefile.PDF";
byte[] abc = System.IO.File.ReadAllBytes(PDFpath);
System.IO.File.WriteAllBytes(PDFpath, abc);
MemoryStream ms = new MemoryStream(abc);
return new FileStreamResult(ms, "application/pdf");
}
>> In the above code you can see PDF file is read as byte format.
>> On memory stream it append the byte code of PDF and retrun as Filestream.
Finally, Run the application.You can clearly see that the right hand side anchor tag open the PDF without append the physical path in browser URL, that makes the physical file to be secure without showing the path. |
</> The Source Code is available in Github.com/CoreProgramm/
Post a Comment