I want to add a PDF file to my .net core 2.0 project, it runs using IIS Express on my localhost, I already add the pdf file to my project file, and it shows up in Solution Explorer, and I added the corresponding link in my .cshtml like this:
<a href=@Url.Content("~/CMT-RPT User Guide.pdf")>Link to guide if it does not show</a><br/>
But after I run it, it cannot show up in my website, what is the problem?
Here are the screen shot of my solution explorer and the website I clicked the link.
Screenshot 1
Screenshot 2
By default, Asp.net core will render static content only from the wwwroot
directory.
The wwwroot
is a special directory to keep all the static assets ( your images/css/js/static files like your pdf etc).
So move your pdf file to the wwwroot
directory and the link will work.
It is possible to specify another directory as the a directory to serve other static content. Let's say you have a directory called MyPdfs
in the app root, you can explicitly add this directory as one of the StaticFile source. To do this, go to your Startup.cs and update the Configure method to have the below code
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Your existing code goes here
app.UseStaticFiles();
// This will add "Libs" as another valid static content location
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyPdfs")),
RequestPath = new PathString("/pdfs")
});
}
The PhysicalFileProvider
class is defined in the Microsoft.Extensions.FileProviders
namespace. So you should add a using statement to that in your Startup.cs
class.
using Microsoft.Extensions.FileProviders;
Now you can have a link which has it's href
attribute pointing to to /pdfs/yourFileName.pdf
You also need to remove the spaces in file name, replace it with _
or -
<a href='@Url.Content("~/pdfs/CMT-RPT_User_Guide.pdf.pdf")'>Link </a>