ASP.Net Core:使用共享项目在多个项目之间共享静态资产(css/js)

Joh*_*ika 7 visual-studio asp.net-core

从这里获取灵感:http : //rion.io/2017/03/22/sharing-is-caring-using-shared-projects-in-asp-net/,我正在尝试使用共享项目来共享静态资产(例如 css / js)在多个 ASP.Net Core 项目之间。

我创建了一个共享项目并在这个文件夹层次结构中添加了这个文件:

在此处输入图片说明

然后,我从我的 ASP.Net Core Web 项目中添加了对这个共享项目的引用。但是,当我运行该项目时,我无法访问此文件。我尝试了这些网址(以及许多其他网址):

http://localhost:50000/assets.style.css
http://localhost:50000/wwwroot/assets/style.css
Run Code Online (Sandbox Code Playgroud)

它们都导致 404。似乎我没有找到在我的 Web 项目中提供这些文件的方法,或者我错误地引用了它们。有谁知道如何使这项工作?

And*_*res 8

我知道这个问题已经有两年了,但我需要在支持两种托管模型(服务器和 WebAssembly)的 blazor 应用程序中共享静态资产,并找到了另一个解决方案。

以防万一,共享项目是一个 Razor 类库。

在此输入图像描述

wwwroot 位于 Ux.Shared 项目上,Ux.Server(Blazor 服务器托管模型)和 Ux.Wasm(Blazor WebAssembly 托管模型)都引用该项目。要在两个项目中使用此资产,您只需使用:

_content/{LIBRARY NAME}/
Run Code Online (Sandbox Code Playgroud)

然后,例如在每个项目的 index.html 中,您可以像这样引用该资产:

 <link href="_content/Ux.Shared/css/bootstrap/bootstrap.min.css" rel="stylesheet" />
Run Code Online (Sandbox Code Playgroud)

这在 Blazor 中工作得很好,我想它在 Asp .Net Core 中也能工作。


Joh*_*ika 6

这是我解决这个问题的方法。我没有使用共享项目,因为我无法让它发挥作用。相反,我使用了PhysicalFileProvider它,它就像魅力一样。

为此,我在src. 我调用它,assets所以我的解决方案资源管理器看起来像这样:

src/assets
src/Foo.Web1
src/Foo.Web2
test/Foo.Tests
Run Code Online (Sandbox Code Playgroud)

我将所有共享的静态资产(例如 css、JavaScript、图像)放在/src/assets. 现在,我映射/src/assetswwwroot/assets文件夹中Foo.Web1,并Foo.Web2使用项目PhysicalFileProvider。在Startup.csConfigure方法中,我添加了以下内容:

if (Env.IsDevelopment())
{
    // app is IApplicationBuilder and Env is IHostingEnvironment
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(Regex.Replace(Env.ContentRootPath, $"{Env.ApplicationName}$", "assets"))),
        RequestPath = new PathString("/assets"),
        OnPrepareResponse = ctx =>
        {
            // Optionally manipulate the response as you'd like. for example, I'm setting a no cache directive here for dev.
            ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

现在,任何请求都/assets将从可以/src/assetsFoo.Web1和共享的文件夹提供服务Foo.Web2。中的所有更改/src/assets都会实时反映。这在开发中效果很好,但在生产方面,我不这样做。相反,我将文件从部署脚本复制/src/assetsFoo.Web1/wwwroot/assets和复制到Foo.Web2/wwwroot/assets部署脚本中,因此不需要进行这种重新映射。