将静态文件包含在可重用的Razor类库中

问题描述 投票:3回答:1

我正在尝试制作可在多个ASP.NET Core MVC项目中使用的可重用类库(RCL)。到目前为止一切顺利……直到我尝试在RCL中包含所需的JavaScript。关于此主题的文档很少。我最好的镜头是try this example

但是当我这样做时,在构建库时出现以下错误:

enter image description here

这是项目文件和库的结构:

enter image description here

感谢您的任何帮助。

javascript asp.net-core asp.net-core-2.1 razor-class-library
1个回答
3
投票

现在我有一些空闲时间,我将回答我自己的问题。也许对某人有用。

最后我使用EmmbededResources解决了这个问题,而没有将EmbeddedFilesManifest设置为ianbusko pointed out in Github

首先,我为IApplicationBuilder类创建了扩展名:

namespace Dashboard.Lib.Extensions
{
    public static class IApplicationBuilderExtension
    {
        public static void UseDashboardScripts(this IApplicationBuilder builder)
        {
            var embeddedProvider = new EmbeddedFileProvider(typeof(Areas.Dashboard.ViewComponents.DashboardViewComponent)
                .GetTypeInfo().Assembly, "Dashboard.Lib.Scripts");

            builder.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = embeddedProvider,
                RequestPath = new PathString("/Scripts")
            });
        }
    }
}

然后我将javascript文件添加到项目文件中:

<PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <GenerateEmbeddedFilesManifest>false</GenerateEmbeddedFilesManifest>
 </PropertyGroup>

 <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
    <PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.1.1" />
 </ItemGroup>

 <ItemGroup>
    <EmbeddedResource Include="Scripts/**/**/**/*" Pack="true" />
 </ItemGroup>

在RCL视图中,JavaScript包含如下:

@section Scripts{
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript" src="~/Scripts/pagination.js"></script>
    <script type="text/javascript" src="~/Scripts/checkdigit-validator.js"></script>
    <script type="text/javascript" src="~/Scripts/rut-validation.js"></script>
}

最后在MVC主项目中的Statup.cs中,您只需要包括以下内容:

app.UseStaticFiles();
app.UseDashboardScripts();
© www.soinside.com 2019 - 2024. All rights reserved.