Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I target .NET Standard 2.0 in a freshly created .NET Core 2.0 web app?

I've just created a fresh project using dotnet new web. My Google-foo may be failing me, but I didn't find anything relating to my answer (please link to another SO answer, or relevant documentation if I've missed something obvious).

If I want to ensure this new project is .NET Standard 2.0 compliant, what do I now do?

like image 932
Geesh_SO Avatar asked Oct 07 '17 14:10

Geesh_SO


2 Answers

NET Standard is for class libraries. Applications must target netcoreapp* where * is a version number. The following shows the compatibility matrix: https://docs.microsoft.com/en-us/dotnet/standard/net-standard

For example, .NET Core 2 can consume .NET Standard version 2 and below.

like image 130
Matt H Avatar answered Sep 30 '22 20:09

Matt H


It is not inherently possible to run a netstandard project as an executable. Since netstandard was designed to be used for libraries.

In order to develop your web application entirely in netstandard2.0, you would have to create a separate project that targets either .NET Core or .NET Framework to execute your library that contains your web app (developed using .NET Standard).

1. Executable Project (ex: console app)
   -- Target Framework: netcoreapp2.0 / net462

2. Web Application Project (library)
   -- Target Framework: netstandard2.0

You can use the following steps to change the target framework of your project.

Step 1. Target the desired framework

  1. Right-click on your project and select Edit *****.csproj

  2. In the .csproj file, you need to replace the target framework to the .NET Framework.

Example .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web"> //<-- note the .Web for the web template
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
</Project>

For a list of the Target Framework Moniker (TFM) (ie, net47, netstandard2.0, netcoreapp2.0, etc.*) you can check this link out: https://docs.microsoft.com/en-us/dotnet/standard/frameworks

Step 2. Run dotnet restore

Go to your output window and run dotnet restore.

Note: Sometimes Visual Studio may misbehave (depending on which update you have installed), so you may have to close and re-open your Visual Studio. Otherwise, sometimes a clean/re-build may do the trick.


Targeting both frameworks

You can pick one or the other, or even target both frameworks.

<TargetFrameworks>netcoreapp2.0; net47</TargetFrameworks> //<-- note the plural form!
like image 21
Svek Avatar answered Sep 30 '22 19:09

Svek