在.NET Core项目中添加PDF链接 [英] Add a PDF link in a .NET Core project

查看:84
本文介绍了在.NET Core项目中添加PDF链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将PDF文件添加到我的.net core 2.0项目中,它使用localhost上的IIS Express运行,我已经将pdf文件添加到我的项目文件中,并且它显示在解决方案资源管理器中,并且我添加了我的.cshtml中的相应链接是这样的:

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.

截屏1

截屏2

推荐答案

默认情况下,Asp.net核心将仅从wwwroot目录呈现静态内容.

By default, Asp.net core will render static content only from the wwwroot directory.

wwwroot是一个特殊目录,用于保留所有静态资产(您的images/css/js/static文件(例如pdf等)).

The wwwroot is a special directory to keep all the static assets ( your images/css/js/static files like your pdf etc).

因此,将您的pdf文件移动到wwwroot目录,该链接将起作用.

So move your pdf file to the wwwroot directory and the link will work.

可以将另一个目录指定为服务其他静态内容的目录.假设您在应用程序根目录中有一个名为MyPdfs的目录,您可以显式将此目录添加为StaticFile源之一.为此,请转到您的Startup.cs并更新Configure方法,使其具有以下代码

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")
     });
}

PhysicalFileProvider类在Microsoft.Extensions.FileProviders命名空间中定义.因此,您应该在Startup.cs类中的该语句中添加一个using语句.

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;

现在您可以拥有一个链接,该链接的href属性指向/pdfs/yourFileName.pdf

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>

这篇关于在.NET Core项目中添加PDF链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆