Define an ASP.NET Core 3.1 controller in another project’s .NET Core class library

1 minute read

Introduction

In ASP.NET Core, you may want to define a Web API that is commonly used by multiple websites in another .NET Core class library project so that you can reuse it.

In the ASP.NET Core 2 series, Nuget had a package that included Microsoft.AspNetCore.Mvc.Controller, so I could add it, reference it, inherit it, and define the MVC controller.

In ASP.NET Core 3.1, there are different ways to do it, so I’ll explain this.

Microsoft.AspNetCore.App Reference Settings

Select Class Library (.NET Core) to create your project.
クラス ライブラリ(.NET Core)

Of course, at this point there is no reference to Microsoft.AspNetCore.App.
ソリューション エクスプローラー

I’ve tried adding Microsoft.AspNetCore as a Nuget package manager, but I can’t find the Version 3.1 series.
NuGet

After researching various things, I arrived at the following site.

According to the exchange on this site, you would add Microsoft.AspNetCore.App as a reference to the framework directly in your .csproj.

.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
  
</Project>

Then, Microsoft.AspNetCore.App is added to [Solution Explorer]-[Dependencies]-[Framework].
ソリューション エクスプローラー

The .NET Core class library project can now reference Microsoft.AspNetCore.Mvc.Controller and inherit it to define the MVC controller.

SharedController.cs



using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreClassLibrary001
{
    public class SharedController : Controller
    {
        [HttpGet("api/Hello/{yourName}")]
        public ActionResult Hello(string yourName)
        {
            return Content($"Hello, {yourName}!!");
        }
    }
}

The result of executing this code is as follows.
Hello