Creating Class Library with Visual Studio for ASP .NET Core Components Not Having a UI
ASP NET Core web applications are highly extensible and customizable with various types of components, such as (but not limied to) middlewares, rewriter rules, tag helpers, view components and razor pages. Sooner or later, you will want to use your custom components in more than one ASP .NET Core project and will need to share them with a class library. Though there is a Razor Class Library project template, it's most probably overkill for components not having a UI.
If you try to add a middleware or a tag helper to a .NET Core Class Library, you will see that classes they inherit or depend on cannot be resolved. In this case, first impulse would be finding and adding the necessary packages to project dependencies. Instead, we will be changing the sdk, class library project uses.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch> </PropertyGroup> </Project>
Above is the contents of a regular .NET Core class library project file crated by Visual Studio (.csproj file). Notice it uses Microsoft.NET.Sdk as project sdk. All we have to do is change it to web sdk so ASP .NET Core dependencies can be resolved.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <TargetLatestRuntimePatch>true</TargetLatestRuntimePatch> </PropertyGroup> </Project>