Blazor WebAssembly中引用ProblemDetails类的构建错误解决方案咨询
在Blazor WebAssembly中正确引用ProblemDetails类的解决方案
问题背景
在Blazor WebAssembly项目中尝试使用ProblemDetails类时,遇到两个编译错误:
- NETSDK1082:类库中使用
<FrameworkReference Include="Microsoft.AspNetCore.App" />后,构建提示There was no runtime pack for Microsoft.AspNetCore.App available for the specified RuntimeIdentifier 'browser-wasm' - CS0234:替换为引用
Microsoft.AspNetCore.Mvc.Core包后,提示The type or namespace name 'ApplicationPartAttributeAttribute' does not exist in the namespace 'Microsoft.AspNetCore.Mvc.ApplicationParts'
解决方法
核心思路是使用官方提供的跨平台专用包,避免引入服务器端AspNetCore框架或Mvc的冗余依赖:
1. 修改类库(ServiceLayer)的.csproj配置
- 移除原有的
<FrameworkReference Include="Microsoft.AspNetCore.App" />节点 - 添加
Microsoft.AspNetCore.Http.ProblemDetailsNuGet包,版本需与Blazor项目中AspNetCore相关包的版本保持一致(示例中为6.0.8) - 统一类库与Blazor项目的第三方包版本(比如FluentValidation),避免版本冲突
修改后的类库.csproj示例:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\DataLayer\DataLayer.csproj" /> <ProjectReference Include="..\BizLogic\BizLogic.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="AutoMapper" Version="12.0.0" /> <PackageReference Include="Dapper" Version="2.0.123" /> <!-- 统一FluentValidation版本与Blazor项目一致 --> <PackageReference Include="FluentValidation" Version="11.7.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.10" /> <PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <!-- 添加ProblemDetails专用包,版本匹配Blazor的AspNetCore版本 --> <PackageReference Include="Microsoft.AspNetCore.Http.ProblemDetails" Version="6.0.8" /> </ItemGroup> </Project>
2. 验证代码
原有的ProblemDetails使用代码无需修改,示例中的反序列化逻辑可以正常运行:
public async Task AddServiceResponsesAsync(List<ServiceResponse> responses) { HttpClient client = _clientFactory.CreateClient(); string uri = _configuration.GetConnectionString("web-api-uri-base-adress"); client.BaseAddress = new Uri(uri); StringContent content = new StringContent( JsonSerializer.Serialize(responses), Encoding.UTF8, "application/json"); var response = await client.PostAsync("service-responses", content); var detailedError = await response.Content.ReadFromJsonAsync<ProblemDetails>(); }
方案说明
Microsoft.AspNetCore.Http.ProblemDetails是官方推出的轻量级包,专门为非服务器场景(如Blazor WASM)提供ProblemDetails和ValidationProblemDetails类,完美支持browser-wasm运行时,从根源解决NETSDK1082错误。- 该包仅包含ProblemDetails相关核心类型,不会引入AspNetCore Mvc的服务器端依赖(如ApplicationParts),因此不会触发CS0234错误。
内容的提问来源于stack exchange,提问作者omike
相关产品推荐
相关产品推荐

