Exploring .NET Core 3.0 and the Future of C# with ASP .NET Core

By Shahed C on December 8, 2018

This is the tenth of a new series of posts on ASP .NET Core. In this post, we’ll explore what’s to come in .NET Core 3.0 and C# 8.0, and what’s new with ASP .NET Core. This post is also included in Matthew Groves‘ 2018 C# Advent Calendar, in the Dec 8 slot.

ASPNETCoreLogo-300x267

WARNING: Be prepared for a lot of information and tons of links to get even more information. 🙂 

In This Article:

Microsoft Connect(); 2018

msft-connect-2018

This past week has given us many exciting announcements and releases from Microsoft Connect(); 2018. This includes the releases of .NET Core 2.2 (with ASP .NET Core 2.2), .NET Core 3.0 Preview 1 and Visual Studio 2019 Preview 1.

You can catch up on what you missed at the following URLs:

What to Expect in .NET Core 3.0

.NET Core 3.0 brings us a slew of new features, notably support for Windows desktop apps (WinForms, WPF) on .NET Core. This will allow “side by side” versions of .NET Core for your desktop apps as opposed to “in-place” framework installations.

Well, how about ASP .NET Core 3.0? Well, during Connect(); 2018, Scott Hunter pointed out that ASP .NET Core 2.2 was also released at the same time as .NET Core 3.0 preview 1. He added that ASP .NET Core 3.0 (preview) within  .NET Core 3.0 (preview) currently has “the exact same ASP .NET Core 2.2 bits” and “so, there’s no benefit to move to 3 yet… won’t be till…. sometime next year [2019]”.

Skip to 8:43 in the following video:


What to Expect in ASP .NET Core 3.0

Here are a few things you can expect in ASP .NET Core 3.0, whenever it comes out next year:

  • Newtonsoft’s Json.NET will be removed from the shared framework
  • EF Core will be shipped separately as pure NuGet packages
  • ASP .NET Core 3.0 will only run on the cross-platform .NET Core 3.0
  • ASP .NET Core 3.0 will NOT run on the Windows-only .NET Framework
  • Note that some new C# 8.0 features will only be coming to .NET Core 3.0

You can get more information on ASP .NET Core 3.0 from an Oct 2018 announcement:

Some additional things you should know about Blazor, the cool kid on the block:

From Daniel Roth (Oct 2018): “We are now working towards shipping Razor Components and the editing in .NET Core 3.0,”… “This includes integrating Razor Components into ASP.NET Core so that it can be used from MVC. We expect to have a preview of this support early next year after the ASP.NET Core 2.2 release has wrapped up.

What’s New in ASP .NET Core 2.2 Right Now

So what’s new in ASP .NET Core 2.2 right now? First of all, you can work with ASP .NET Core 2.2 in the latest version of Visual Studio 2017 or VS Code with the .NET Core 2.2 SDK. There are many cool new features, notably:

  • New Health Checks API
  • Improved Open API (Swagger) Integration
  • Client-side template updates (Bootstrap 4, Angular 6)
  • SignalR Java Client
  • HTTP/2 Server Support (Preview)
  • Improved perf: IIS throughput, MVC model validation + routing, HTTP Client

You can read the full announcement here:

You can get also a recap of the API improvements and Health Checks API in this video from Connect:


Health Checks

From the aforementioned Github repo, here is a code snippet for the new Health Checks feature:

public void ConfigureServices(IServiceCollection services)
{
   ...
   services.AddHealthChecks()
      .AddDbContextCheck<PlacesContext>();
   ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ... 
   app.UseHealthChecks("/ready");
   ...
}

In the above snippet, the call to AddHealthChecks() followed by AddDbContextCheck() ensures that the data connection is healthy before determining that the application is healthy. The route /ready can be accessed in a browser or externally to determine the health of the application.

Open API (Swagger)

Features for using Open API (Swagger) with ASP .NET Core was already included in ASP .NET Core 2.1 and has further improved with ASP .NET Core 2.2. As before, you can use community-driven projects such as NSwag and Swashbuckle.AspNetCore to visualize Open API documents for your API.

Benefits include:

  • interactive documentation
  • client SDK generation
  • API discoverability

So what’s new in 2.2? We now have Microsoft.AspNetCore.Mvc.Api.Analyzers, which work with [APIController]-decorated controllers introduced in 2.1, and also builds on API conventions. With this package added to a new Web API project, my .csproj project file looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web"> 
<PropertyGroup>
 <TargetFramework>netcoreapp2.2</TargetFramework>
 <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
 </PropertyGroup> 
<ItemGroup>
 <PackageReference Include="Microsoft.AspNetCore.App" />
 <PackageReference Include="Microsoft.AspNetCore.Mvc.Api.Analyzers" Version="2.2.0" />
 <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
 </ItemGroup> 
</Project>

So what do these new analyzers do? One example can be explained by starting with the code snippet below:

 // GET api/values/5
 [HttpGet("{id}")]
 [ProducesResponseType(200)]
 public ActionResult<string> Get(int? id)
 {
    if (id == null)
    {
       return NotFound();
    }
    return "value";
 }

In this simple Get method in my API Controller, it returns an HTTP 200 (Success!) Status Code when everything is going well, which is indicated by [ProducesResponsesType(200)]. But if the id value is null, it returns NotFound(). In this case, the analyzer can automatically guide you to add the proper attribute for a HTTP 400 (Not Found) Status Code as well.

See this illustrated in the GIF below:

API Analyzer Example

API Analyzer Example

Here is the end result:

 // GET api/values/5
 [HttpGet("{id}")]
 [ProducesResponseType(200)]
 [ProducesResponseType(StatusCodes.Status404NotFound)]
 [ProducesDefaultResponseType]
 public ActionResult<string> Get(int? id)
 {
    if (id == null)
    {
       return NotFound();
    }
    return "value";
 }

If you use common API Conventions, you can make your life even easier by using Conventions. Conventions can be applied via attributes in 3 different ways: at the assembly level, at the controller level and at the method level, each deeper level superseding the attribute at the higher level. These can then be superseded by ProducesResponseType applied at an action level.

Three examples are shown below:

At the assembly level:

[assembly: ApiConventionType(typeof(DefaultApiConventions))]

At the controller level, e.g. ItemsController

[ApiConventionType(typeof(DefaultApiConventions))]
[ApiController]
[Route("/api/[controller]")]
public class ItemsController : ControllerBase
{
   ...
}

At the method level, e.g. PutItem()

// PUT: api/items/5
[ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Put))]
[HttpPut("{id}")]
public async Task<ActionResult<Item>> PutItem(long id, Item item)
{
   ...
}

For more information, check out the official announcement from August 2018:

What’s New in EF Core 2.2 & 3.0

EF Core 2.2 includes some new features and a ton of bug fixes. New features include:

  • Spatial data support: used to represent the physical location and shape of objects
  • Collections of owned entities: extends the ability to model ownership to 1-to-many associations, going beyond 1-to-1 associations (previously added in 2.0)
  • Query tags: allows you to annotate a LINQ query with a string of text that appears as comments in generated SQL output (which may be captured in logs)

EF Core 3.0 will bring several new features:

  • LINQ improvements
  • Cosmos DB support
  • C# 8.0 support
  • Reverse engineering database views into query types
  • Property bag entities
  • EF 6.3 on .NET Core

These are all explained in detail in the official announcement:

What to Expect in C# 8.0

From one of the C# 8.0 announcements“The current plan is that C# 8.0 will ship at the same time as .NET Core 3.0. However, the features will start to come alive with the previews of Visual Studio 2019”.

Here are some new features you can expect in C #8.0:

  • Nullable Reference Types: get a friendly warning if you try to assign non-nullable reference types to null. This setting can be toggled, to assist in future projects and also provide warnings in existing projects. In other words, C# 8.0 allows you to express “nullable intent”.
string myString = null; // Friendly Warning!
string? myString = null; // This is ok
  • IAsyncEnumerable<T> for consumption of async streams: It is essentially an asynchronous version of IEnumerable<T>, allowing you to await foreach over the items in an async stream.
async IAsyncEnumerable<int> GetBigResultsAsync()
{
   await foreach (var result in GetResultsAsync())
   {
      if (result > SomeValue) yield return result; 
   }
}
  • Ranges and Indices: A new Index type and a .. (two dots) range feature bring in the ability to easily slice through subsets of ranges of values. You may have missed such a feature in C# if you’ve worked with Python to manipulate your data.
// for an array of ints
int[] myArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Index index1 = 3; // 0-index, number 3, counted from beginning
Index index2 = ^4; // 4th item from end, counting backwards 

Console.WriteLine($"{myArray[index1]}, {myArray[index2]}"); // "3, 6" 

var mySlice = myArray[index1..index2]; // { 3, 4, 5 } not including end 

When I used the above code in Visual Studio 2019 Preview 1, I had to update my .csproj to use C# 8.0. Take a look at the example below:

<Project Sdk="Microsoft.NET.Sdk"> 
<PropertyGroup>
 <OutputType>Exe</OutputType>
 <TargetFramework>netcoreapp3.0</TargetFramework>
 <LangVersion>8.0</LangVersion>
 </PropertyGroup> 
</Project>
  • Default implementations of interface members: this gives you the ability to add a real implementation of an interface member that will be used by any class that implements the interface but doesn’t explicitly define the member in its class. Existing classes will automatically get this implementation.
interface ILogger
{
   // method 1 defined in interface 
   void Log(LogLevel level, string message);
   
   /// method 2 can be added to interface, even after class was created
   void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); 
} 

class ConsoleLogger : ILogger
{
   // method 1, explicitly implemented in class   
   public void Log(LogLevel level, string message) { ... }
  
   // method 2, Log(Exception) gets default implementation
}

You can get more information on C# 8.0 features at:

References, Docs & Tutorials

New/Updated Downloads:

.NET Core 3 and ASP .NET Core 3.0 References:

ASP .NET Core 2.2 Tutorials, Samples and Docs:

Open API (Swagger) References 

ASP .NET Core 3.0

C# 8.0 Tutorials, Samples and Docs:

References for Microsoft Connect(); (Dec 4, 2018)

8 thoughts on “Exploring .NET Core 3.0 and the Future of C# with ASP .NET Core

  1. Pingback: Exploring .NET Core 3.0 and the Future of C# with ASP .NET Core - How to Code .NET

  2. Pingback: Dew Drop - December 10, 2018 (#2856) - Morning Dew

  3. Pingback: 1 – The Second Annual C# Advent | Traffic.Ventures Social

  4. Pingback: API Controllers in ASP .NET Core | Wake Up And Code!

  5. Ali

    Good,

    but why should Core 3 comes with Angular 6 as mentioned here :

    – Client-side template updates (Bootstrap 4, Angular 6)

    Angular 7 is already here so why?.

    Reply
  6. Pingback: Summarizing Build 2019 + SignalR Service for ASP .NET (Core) Developers | Wake Up And Code!

  7. Pingback: Happy New Year 2019! | Wake Up And Code!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.