Include static files in a reusable Razor Class Library

Viewed 1471

I am trying to make a reusable class library (RCL) that I can use in several ASP.NET Core MVC projects. So far so good… until I try to include the required JavaScript in the RCL. There is little-to-no documentation about this topic. My best shot was to try this example.

But when I do, I get the following error when I build the library:

enter image description here

This is the project file and the structure of the library:

enter image description here

Any help is appreciated.

1 Answers

Now that I have some spare time I will answer my own question. Maybe it will useful for someone.

Finally I solved this problem using EmmbededResources without the EmbeddedFilesManifest as ianbusko pointed out in Github.

First I created an extension for the IApplicationBuilder class:

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

Then I added the javascript files to the project file:

<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>

In the RCL view the javascript is included as follows:

@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>
}

Finally in the Statup.cs in the main MVC project you just have to include the following:

app.UseStaticFiles();
app.UseDashboardScripts();
Related