How to use ASP.NET Core 5 APIs in a class library?
UPDATE (11/Nov/2022): the correct way to do this is now officially documented here.
The article goes into a lot of detail but the focus seems to be on target framework netcoreapp3.0 - there's no mention of target framework net5.0 so here is what I tried on my own:
I created a C# class library using the standard template and targeting net5.0. I then unloaded the project and edited the project file to read as follows:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<OutputType>Library</OutputType>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
</PropertyGroup>
</Project>
...when I reloaded the project Visual Studio was happy to load my class library project and it looked like this (just like an ASP.NET Web API project would look):

I was then able to test that ASP.NET APIs can be used by moving the following Startup.cs file into the class library:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace AspNetClassLibTest
{
public class StartupLib
{
public void ConfigureServices(IServiceCollection services) { }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapGet("/", async context => {
await context.Response.WriteAsync("Hello World from lib!");
});
});
}
}
}
I referenced the class library in my ASP.NET Web API project and it looked as follows:

The Program.cs file references the StartupLib class defined in the class library:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace AspNetClassLibTest
{
public class Program
{
public static void Main(string[] args) {
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<StartupLib>(); // <----- reference class from class library.
});
}
}
Running the Web API project produces the expected output:

This seems to be working (my house hasn't blown up) as I expect, but I am wondering if there's something I am missing that could come back to cause me grief down the line?
My use case is as follows: I have 9 different Web API projects and all of them have almost identical code in the Startup.cs file so I wanted to move that ASP.NET-related code to a class library and reuse it in all projects.
If the process I followed above is the correct way to do this for ASP.NET Core 5 projects, then it would be helpful to update the docs (I am happy to do a PR based on the above steps if they can be confirmed to be correct) :+1:
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 98629146-7d64-9f48-6e45-51bafe8c7116
- Version Independent ID: cdb2b89f-bf1c-f313-0062-7f6b7ef8b611
- Content: Use ASP.NET Core APIs in a class library
- Content Source: aspnetcore/fundamentals/target-aspnetcore.md
- Product: aspnet-core
- Technology: aspnetcore-fundamentals
- GitHub Login: @Rick-Anderson
- Microsoft Alias: scaddie
UPDATE (25 days later): this has worked very well so far (house still hasn't blown up).
There is one little snag: each time you open a solution containing a class library using ASP.NET Core 5 APIs, Visual Studio insists on creating a launchSettings.json file for that project, which doesn't make sense because you can't run a class library...if you try to, you get this message:

I usually just delete the file, though I imagine its harmless to leave it there just to prevent Visual Studio from trying to recreate it each time :+1:
@Rick-Anderson is there a way to suppress this? Maybe the IDE/project system team needs to be made aware because normally Visual Studio gives a clear error message when you try to run a class library project:

I usually just delete the file, though I imagine its harmless to leave it there just to prevent Visual Studio from trying to recreate it each time 👍
I just read Andrew Lock's blog where he writes about how you can stop the launchsettings file being created How to stop Visual Studio from creating launchsettings.json
Just add
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
to the csproj file.
@martinstenhoff thanks a lot for sharing that tip, it works like a charm!
I have updated the instructions on how to edit the project file, so it now includes <NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
Alternative solution (that seems to work at least):
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectCapability Include="AspNetCore" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
This does not turn your project into a "web project". Not going to pretend to know why this works. But it seems to do so without problems. Both from command line, and in VS:

@Alxandr: Not going to pretend to know why this works.
It appears project capabilities are documented here and the known capabilities are here yet somehow AspNetCore is not on that list. Despite being open source (see VSProjectSystem and dotnet/project-system) the project system seems to possess mysterious powers (like <NoDefaultLaunchSettingsFile> mentioned by @martinstenhoff above) that only a few people seem to understand!
@Alxandr Are you sure <ProjectCapability Include="AspNetCore" /> is needed? I seem to run just fine without it, I only added <FrameworkReference Include="Microsoft.AspNetCore.App" />. My usages are mainly ActionResult, ModelStateDictionary and similar types.
It did not work without it for me. It didn't find the framework.
This is the minimal project structure I'm currently testing out, seems to work well here with SDK 5.0.302. Using Rider as IDE, not Visual Studio, if that matters.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
I'm using Visual Studio. It didn't work for me. Might be other reasons though.
@Alxandr I face with the same issue, make sure that you register app.UseRouting(); before you Middleware
This has nothing to do with middleware. There's not even an application involved. We're just talking about referencing DLLs.
So in the end this ends up being the same for .NET 5 as it was for .NET Core 3.x right?
Yes
And I'm using it successfully in the .NET 6 RC.