Telerik blogs
W3CKRsb

Catch all the latest news about the RC release of ASP.NET Core 2.1 in Ed Charbeneau's interview with Daniel Roth at Microsoft Build 2018.

On this episode of Eat Sleep Code, guest Daniel Roth talks about the "live release candidate" of ASP.NET Core 2.1. I sat down with Daniel Roth at Microsoft Build 2018 to discuss what improvements are coming in the release, and there’s a lot to talk about. It’s an exciting release that includes a brand spanking new SignalR/Azure SignalR, easy integration with OpenAPI (aka Swagger), Functional Testing support, and much more. Daniel discusses some of his favorite features like HttpClientFactor and experimental frameworks like Blazor.

You can listen to the show, recorded live at Build 2018, using the player below or by subscribing on iTunes. For those who prefer reading to listening, included below are recaps of many of the features discussed on the podcast.

SignalR

SignalR is an ASP.NET library for working with bi-directional communication between the server and client using Websockets. In ASP.NET 2.1 the new version of SignalR is a fully featured live release. While SignalR wasn’t completely rewritten from the initial .NET Framework version, it has been fundamentally changed and significantly improved. One of the biggest changes is the removal of its jQuery dependency. Removing jQuery broadens the spectrum of client-side frameworks to use including Angular, React, and Vue. In addition, protocols are now extensible in SignalR along with two built-in hub protocols: a text protocol based on JSON and a binary protocol using MessagePack.

Azure SignalR Service

One of the biggest announcements surrounding SignalR is how it’s being included in the Azure stack. Developers no longer need to manage performance, scalability, and availability from their SignalR hubs. With the Azure SignalR Service these issues are handled for you.

signalr

The Azure SignalR service is tightly integrated with the SignalR .NET library. Adding Azure SignalR to an existing SignalR implementation is done by creating a reference to the Azure SignalR Service SDK.

Install-Package Microsoft.Azure.SignalR -Version 1.0.0-preview1-10009

Next, configure a connection string and wire up services in Startup.cs using services.AddSignalR().AddAzureSignalR() and app.UseAzureSignalR(). Existing ASP.NET Core SignalR clients do not require modification to take advantage of Azure SignalR Services.

OpenAPI / Swagger Integration

In this release, a new method of making ASP.NET Core Web APIs more descriptive using the OpenAPI specification (formerly Swagger) was added. This was done to alleviate the need for using multiple attributes to produce similar results when using IActionResult. ASP.NET Core 2.1 introduces a new ActionResult type that allows either the response type or any action result to be returned while still indicating the response type.

[Produces(typeof(SalesOrder))]
public IActionResult Get(long id)
{
  var salesOrder = GetSalesOrder(id);
  return Ok(salesOrder);
}

public ActionResult<SalesOrder> Get(long id)
{
  var salesOrder= GetSalesOrder(id);
  return salesOrder;
}

When using ActionResult<T> the return object is defined by T and the OpenAPI specification can be obtained from the method signature.

Functional Testing Support

Functional testing has gotten easier in ASP.NET Core 2.1 with WebApplicationFactory. WebApplicationFactory will invoke the entire application and host it in memory. WebApplicationFactory allows developers to create a custom factory that configures the HttpClient without "touching the wire." When WebApplicationFactory is initialized it will invoke the entire app end-to-end, including pages and views, so the results can be checked. This enables testing scenarios that require specific HttpClient configuration, for example, adding specific HTTP headers to a request.

HttpClientFactory

HttpClientFactory is an "opinionated" factory for creating HttpClient instances to be used in your applications. It provides guidance to using HttpClient such that HttpClient is efficiently created and reused versus disposing of them prematurely. Misuse of HttpClient can cause significant bottlenecks and poor reliability by consuming resources and sockets. In addition to providing HttpClient as an .NET service, the factory manages cross cutting concerns via a request pipeline in a centralized way.

HttpClientFactory introduces named and typed clients for using multiple distinct instances of HttpClient.

Using the AddHttpClient method a named HttpClient is added to the service container.

public void ConfigureServices(IServiceCollection services) {
  services.AddHttpClient("github", c =>
  {
    c.BaseAddress = new Uri("https://api.github.com/");

    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); // Github API versioning
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); // Github requires a user-agent
  });
}

The httpClientFactory is then resolved through dependency injection and an instance of the named client is created.

public class MyController : Controller
{
  IHttpClientFactory _httpClientFactory;

  public MyController(IHttpClientFactory httpClientFactory)
  {
    _httpClientFactory = httpClientFactory;
  }

  public IActionResult Index()
  {
    var gitHubClient = _httpClientFactory.CreateClient("github");
    return View();
  }
}

HttpClient can also be strongly typed for additional IntelliSense and compiler help. A strongly typed HttpClient is added to the service container using AddHttpClient<T>.

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient<GitHubService>();
    services.AddMvc();
}

A custom class encapsulates the necessary headers and settings needed for making the request.

public class GitHubService
{
  public HttpClient Client { get; private set; }

  public GitHubService(HttpClient client)
  {
    client.BaseAddress = new Uri("https://api.github.com/");
    client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json"); // Github API versioning
    client.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample"); // Github requires a user-agent

    Client = client;
  }
}

In the controller, the HttpClient can be resolved through dependency injection using the type.

public class IndexModel : PageModel
{
  private GitHubService _ghService;

  public IndexModel(GitHubService ghService)
  {
    _ghService = ghService;
  }

  public async Task OnGet()
  {
    var result = await _ghService.Client.GetStringAsync("/orgs/octokit/repos");
  }
}

With the addition of HttpClientFactory an outgoing HTTP middleware pipeline is available using a DelegatingHandler type. The outgoing middleware pipeline is conceptually similar to how ASP.NET handles incomming HTTP requests. More infromation about the HttpClientFactory is available in the article, Introducing HTTPClient factory.

Razor Class Libraries

A Razor Class Library (RCL), as the name imples, is a class library that contains compiled Razor views. RCLs are a simple way to create reuseable chucks of view code that can be shared between projects or via NuGet. Included in the ASP.NET Core 2.1 release is a new RCL template available through the File > New Project experience in Visual Studio or the commandline using dotnet new razorclasslib -o RazorClassLib1.

razor-class-library

This new way of sharing ASP.NET MVC views creates opportunities for the ASP.NET community to share common UI patterns.

If you have an idea for how Progress Telerik can utlize RCLs, drop us a line at feedback.telerik.com and let us know.

Identity Overhaul

Identity in ASP.NET Core 2.1 is getting a major overhaul.

GDPR

Updates include support that will enable developers to deal with implications of General Data Protection Regulation (GDPR), which enables users take control of their personal data. In this release the ASP.NET Identity library gives developers a starting point for how to deal with cookies, the ability to download personal data (take it offline), and delete their identity data.

Identity Scaffolding

In prevous versions of ASP.NET Core, adding Identity to a project was a very manual process. Users often needed to create a new project using the File > New Project dialog to obtain the necessary code to add to an existing project. With ASP.NET Core 2.1 and thanks to Razor Class Libraries (RCL), this is now a simple process.

In ASP.NET Core 2.1 Identity is a RCL that can be added to new and exsting project with ease. To further assist developers with the process, a new Identity scaffolidng wizard was added to Visual Studio. The Identity scaffolding tool serves two purposes, adding Identity or overriding existing Identity templates.

identity-scaffolding

Since the Identity views are contained within a RCL, they can’t be editied directly. This is where the Identity scaffolder really shines, as it can be used to generate the views using an intuitive interface. Developers simply check boxes coresponding to the views they would like to override and add them to the project. Once the files are added to the project, any file on disk that occupies the same path as a view found in the RCL will override the RCL.

New SPA templates

ASP.NET Core 2.0 added new Single Page Application (SPA) templates for Angular and React. In ASP.NET Core those templates have been superseded with new templates which are compatible with the Angular CLI and React create-react-app command line experiences. The new SPA templates offer an easy on-boarding experience for Angular and React development using .NET technologies.

Note: Missing from the new templates is Server Side Rendering (SSR). SSR can be enabled, but it’s not a decision to be taken lightly as there are negative impacts to using SSR in an application. Details regarding SSR with ASP.NET Core 2.1 SPA Templates can be found in the official ASP.NET documentation.

If you’re a Progress Telerik customer and would like to try the Angular SPA template using Kendo UI, download our latest extension for Visual Studio from the marketplace. Let us know if this is something we should continue to develop by leaving your feedback at feedback.telerik.com.

Blazor Experiment Continues

Blazor is not officially a supported ASP.NET Core feature, but that doesn’t make it any less exciting. Blazor is a new experimental .NET web framework using C#/Razor and HTML that runs in the browser with WebAssembly. Blazor is heavily inspired by concepts of popular frontend frameworks like Angular and React. The promising aspect of Blazor is that it’s capable of consuming .NET Standard libraries on the browser client. This means that Blazor apps can potentially share common code between server and client, and additionally libraries from NuGet. The caveat to running existing libraries on the client is they must not be dependent on resources that aren’t available in the browser, ex: System.IO or System.Drawing.

Since Blazor is an experiment, it must be added manually and is not included with ASP.NET Core 2.1. You can find installation instructions on the Blazor home page.


About the Author

Ed Charbeneau

Ed Charbeneau is a web enthusiast, speaker, writer, design admirer, and Developer Advocate for Telerik. He has designed and developed web based applications for business, manufacturing, systems integration as well as customer facing websites. Ed enjoys geeking out to cool new tech, brainstorming about future technology, and admiring great design. Ed's latest projects can be found on GitHub.

Related Posts

Comments

Comments are disabled in preview mode.