若要在非web.sdk项目中使用ASP.NET Core 3+类型,请使用shared framework reference.
示例项目:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net6.0</TargetFrameworks>
<Nullable>enable</Nullable>
<OutputType>Library</OutputType>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
然而,请注意,这主要是为了为库提供端点等.在业务层使用此引用可以将业务逻辑与Web API框架结合起来.
更灵活的方法是为业务逻辑项目中所需的功能提供接口,并在API项目中提供实现.
举个例子
// In business project
public interface IMySpecialContext
{
string Value { get; }
}
// In API project
public class HttpMySpecialContext : IMySpecialContext
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HttpMySpecialContext(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public string Value
{
// Probably should throw for missing HttpContext or header.
get => _httpContextAccessor.HttpContext?.Request.Headers["X-My-Special-Header"]!;
}
}
// In unit tests
public class DummyMySpecialContext : IMySpecialContext
{
public string Value => "Dummy Special Context Value";
}