You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NuGet包静态资源在project.assets.json存在但访问404的解决方法

解决Blazor WebAssembly NuGet包静态资源404问题

你当前将CSS文件打包到Nu包的content/css目录,但Blazor WebAssembly项目不会自动将Nu包content目录下的文件作为静态Web资产托管,导致访问时出现404。正确的做法是通过**静态Web资产(Static Web Assets)**机制打包资源,让目标项目自动识别并加载这些资源。

1. 修正NuSpec文件配置

修改nuspec的<files>和<contentFiles>节点,将静态资源指向Blazor静态Web资产的标准路径:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
  <metadata>
    <id>Client1</id>
    <version>1.2.53</version>    
    <title>Client1</title>
    <description>Desc</description>
    <authors>mz</authors>
    <owners>me</owners>    
    <requireLicenseAcceptance>false</requireLicenseAcceptance>    
    <releaseNotes>notes</releaseNotes>
    <copyright></copyright>
    <tags></tags>
    <dependencies>
      <dependency id="Microsoft.AspNetCore.Components.Web" version="8.0.0" />
      <dependency id="Microsoft.AspNetCore.Components.WebAssembly" version="8.0.0" />
      <dependency id="MudBlazor" version="6.12.0" />    
    </dependencies>
    <summary></summary>
    <contentFiles>      
      <files include="any/net8.0/wwwroot/css/*.css" buildAction="Content" copyToOutput="true" />
    </contentFiles>
  </metadata>
  <files>    
    <file src="wwwroot\css\*.css" target="contentFiles\any\net8.0\wwwroot\css" />  
    <file src="bin\Release\net8.0\Client1.dll" target="lib\net8.0" />            
  </files>
</package>

注意:

  • 移除了NuGet.Build.Tasks.Pack和Microsoft.AspNetCore.Components.WebAssembly.DevServer依赖,这两个是开发/打包工具,无需作为Nu包的运行时依赖。
  • 静态资源路径改为contentFiles/any/net8.0/wwwroot/css,符合Blazor静态Web资产规范。

2. 修正Client1.csproj配置

当前csproj中的NoBuild设置会导致无法正确生成静态Web资产,需要调整:

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"> 
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>    
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyVersion>1.0.0.8794</AssemblyVersion>    
    <StaticWebAssetBasePath>Client1</StaticWebAssetBasePath>   
    <IsPackable>true</IsPackable>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <!-- 移除NoBuild,否则无法编译项目生成正确的静态资产 -->
    <IncludeBuildOutput>false</IncludeBuildOutput>
    <NuspecFile>$(SolutionDir)\Client1\Client1.nuspec</NuspecFile>   
  </PropertyGroup>
</Project>

3. 重新打包并安装NuGet包

  • 清理项目编译文件:
    dotnet clean
    
  • 生成Release版本并打包:
    dotnet build --configuration Release
    
  • 在目标项目中卸载旧版本Client1 Nu包,重新安装新生成的包。

4. 访问静态资源的正确路径

安装完成后,静态资源会被目标项目的静态Web资产机制托管,正确访问路径为:
https://localhost:nnnn/_content/Client1/css/app.css

说明:Blazor中Nu包的静态Web资产默认挂载到_content/{Nu包ID}/路径下,而非直接的content/路径。

内容的提问来源于stack exchange,提问作者mz1378

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:33:15