Search code examples
c#asp.netasp.net-corecsproj

ASP.NET Core View Not Found in a class library (Microsoft.Net.Sdk without .Web)


I'd like to have a Microsoft.Net.Sdk project that launch a web server using asp.net core. It is a normal dll project, not a Web project. The csproj header is the following:

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

And in order to make it work I added (see docs):

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

The web server is launched correctly but the Views don't work, I always have the View Not Found exception. The views are in the right places and are Content file.

If I change from <Project Sdk="Microsoft.NET.Sdk"> to <Project Sdk="Microsoft.NET.Sdk.Web"> everything works fine.

I think I have to add some packages or FrameworkReference to my csproj but I couldn't find anything. Any ideas?


Solution

  • I solved this issue by switching to the recommended SDK tag for ASP.NET Core projects:

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

    Initially I thought that using that mode in a class library project would bring up other issues, but I was only partially right: switching to the Microsoft.NET.Sdk.Web SDK changes the project output type to Exe (not a class library anymore), so it will start complaining about a missing Main() method.

    But the easy part is that you can override this behaviour by setting the OutputType property:

    <Project Sdk="Microsoft.NET.Sdk.Web">
      <PropertyGroup>
        <TargetFramework>net5.0</TargetFramework>
        <!-- Explicitely override this setting because Microsoft.NET.Sdk.Web sets it to Exe -->
        <OutputType>Library</OutputType>
      </PropertyGroup>
    

    Moreover, you don't need to include the Microsoft.AspNetCore.App framework so you should delete this part:

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