AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

How to use ASP.NET Core 5 APIs in a class library?

Open ericmutta opened this issue 5 years ago • 14 comments

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):

image

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:

image

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:

image

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.

ericmutta avatar Apr 13 '21 19:04 ericmutta

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:

image

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:

image

ericmutta avatar May 09 '21 01:05 ericmutta

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 avatar Jun 09 '21 20:06 martinstenhoff

@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>

ericmutta avatar Jun 10 '21 14:06 ericmutta

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:

image

Alxandr avatar Jul 01 '21 20:07 Alxandr

@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!

ericmutta avatar Jul 02 '21 19:07 ericmutta

@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.

angularsen avatar Jul 22 '21 23:07 angularsen

It did not work without it for me. It didn't find the framework.

Alxandr avatar Jul 23 '21 06:07 Alxandr

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>

angularsen avatar Jul 23 '21 08:07 angularsen

I'm using Visual Studio. It didn't work for me. Might be other reasons though.

Alxandr avatar Jul 23 '21 10:07 Alxandr

@Alxandr I face with the same issue, make sure that you register app.UseRouting(); before you Middleware

Svmurvj avatar Aug 19 '21 19:08 Svmurvj

This has nothing to do with middleware. There's not even an application involved. We're just talking about referencing DLLs.

Alxandr avatar Aug 20 '21 10:08 Alxandr

So in the end this ends up being the same for .NET 5 as it was for .NET Core 3.x right?

AndrewTriesToCode avatar Sep 19 '21 23:09 AndrewTriesToCode

Yes

davidfowl avatar Sep 19 '21 23:09 davidfowl

And I'm using it successfully in the .NET 6 RC.

Tragetaschen avatar Oct 14 '21 11:10 Tragetaschen