8 Must-Know NuGet Packages for an ASP.NET Core Application

8 Must-Know NuGet Packages for ASP.NET - Ozcode
Here are some of the most popular NuGet packages used in ASP.NET Core applications. Use these packages to get a running start on your project.

When a new framework or technology first appears, it’s like the wild west. Everyone’s doing their own thing, trying to figure out the best way to build a product. That’s not the case with the ASP.NET framework. We’ve been going at it since 2002, living through Web Forms, MVC, and Web API. We made every mistake possible and learned from it. I’m not saying we figured everything out and achieved perfection, but we do have experience and proven methodologies that work well. In this article, I’ll go over some of the most popular NuGet packages used in ASP.NET Core applications. Those packages became popular for good reasons, and using them will give you a running start on your projects.

1. Swahshbuckle.AspNetCore

Swashbuckle is the toolset that adds Swagger support to your application (now called OpenAPI). If you’re building a REST Web API server, Swagger provides you with some very valuable services. It will automatically generate a JSON object that describes your entire API. This includes the endpoints, the models, and the possible results. From that JSON, Swashbuckle produces a beautiful UI and documentation that you can view when entering the default address mysite.com/swagger. Here’s what it looks like for the Ozcode Production Debugger server:
Ozcode Server Swagger - Ozcode

Besides the automatic documentation that is always up to date, you can also generate clients automatically. You’ll be able to create a DLL which you can reference in your C# client application. Once generated and referenced, instead of using HttpClient, just call methods in the generated client project.

Find Swashuckle.AspNetCore  on NuGet Gallery

2. AutoMapper

When dealing with APIs, you’re constantly going back and forth from database models, to DTO models. DTO stands for Data Transfer Object and it’s when you want the client to use a different schema from the one in your database. There are many reasons  to do that. For example, you may want to provide less information to the client, organize it differently, and perhaps, most importantly, to decouple the database from the REST service. After all, if you change something in your server, you don’t necessarily want to change all your clients along with it.

Automapper provides an easy way to transform one type of object to another. In our case, it will usually be a persistent model to a DTO model.

At startup:

var configuration = new MapperConfiguration(cfg =>  
{
    cfg.CreateMap<Bar, BarDto>()
        .ForMember(dto => dto.Address, expression => expression.MapFrom(bar => bar.UserAddress));
});

In business logic, executing the transformation is as easy as:

var barDto = mapper.Map<BarDto>(bar);

 

Find AutoMapper on NuGet Gallery

3. Entity Framework

I can’t possibly write a post like this without mentioning EntityFramework (EF) and EntityFrameworkCore. It’s the most widely used ORM in .NET by far, with over 100 million downloads for each package. The basic usage is to be able to map C# objects to database entities (tables). Then, you can use LINQ to query these database entities like regular collections. EF produces SQL under the hood, and the whole experience is seamless and quite magical. In addition to Microsoft’s SQL Server, Entity Framework also works with PostgreSQL, SQLite, CosmosDB, MySQL, Oracle, and others. But working with EF isn’t the only option to work with databases. You can go old-school and work with raw SQL with ADO.NET and stored procedures. It’s going to take much longer to develop, but you can achieve crazy performance. Of course, stored procedures have their own issues when you have too many of them (complexity, debuggability, extensibility, etc.).
Find EntityFramework and EntityFrameworkCore on NuGet Gallery

Enhance Visual Studio Debugging - Ozcode

4. Dapper

Dapper is another alternative to Entity Framework. It provides a way to write raw SQL and easily map it to C# objects. Kind of like ADO.NET, except for the mapping to objects part. “Why use it?” you might ask. Performance is the main reason, but Dapper is also very flexible. Dapper is much faster than EF in certain scenarios and even a little faster than ADO.NET raw SQL, according to this benchmark. So Dapper is somewhere between Entity Framework and ADO.NET. You still have to write SQL queries, but it’s much easier to use than ADO.NET. You can choose to use Dapper and Entity Framework together. The performance-sensitive parts can be developed with Dapper and the rest with EF. Here’s a small taste:
string sql = "SELECT TOP 10 * FROM OrderDetails"; 
using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools())) 
{ 
      var orderDetails = connection.Query(sql).ToList();      
      FiddleHelper.WriteTable(orderDetails); 
}
Find Dapper on NuGet Gallery

5. MediatR

MediatR is the most popular mediator pattern implementation in .NET.

Mediator Pattern - Ozcode “What’s the mediator pattern?” you might ask. It’s a way to send messages between classes with no dependencies on one another. Those messages might be classified as notifications, commands, or requests/responses. They might be synchronous or asynchronous. Here’s an example of a simple notification. First, install the packages MediatR and MediatR.Extensions.Microsoft.DependencyInjection. Add MetiatR in Startup services:
public void ConfigureServices(IServiceCollection services) 
{ 
    // ... 
    services.AddMediatR(typeof(Startup)); 
}
Create a notification message:
public class Ping : INotification { }
Create a handler for the notification (you can have multiple)
public class PingHandler : INotificationHandler{ 
    public Task Handle(Ping notification, CancellationToken cancellationToken) 
    { 
        Debug.WriteLine("handled"); 
        return Task.CompletedTask; 
    } 
}
Now you can publish the notification anywhere:
public class MyController : ControllerBase 
{ 
    private readonly IMediator _mediator;
public SignInUpController(IMediator mediator) { _mediator = mediator; } [HttpGet] public async Task Foo() { await _mediator.Publish(new Ping()); return Ok(); } }

Find MediatR on NuGet Gallery

Enhance Visual Studio Debugging - Ozcode

6. RestSharp

RestSharp is an HTTP client. It allows you to make HTTP requests, much like the built-in HttpClient. Except that it’s actually simple and convenient. Here is an example. I’m sending a simple POST request to a server. Here’s how it looks with RestSharp:

var client = new RestClient("https://localhost:5003/"); 

var request = new RestRequest("Login/SignUp", DataFormat.Json);
request.AddJsonBody(new SignUpViewModel() { Email = "aaa@gmail.com" });
SignUpResponse response = await client.PostAsync<SignUpResponse>(request);
Console.WriteLine($"response = {response.Token}");

Nice, clean, and intuitive, right?

On the other hand, here’s how it looks with HttpClient:

var data = new SignUpViewModel() { Email = "aaa@gmail.com" }; 
var client = new HttpClient();
var dataAsString = JsonConvert.SerializeObject(data);
var content = new StringContent(dataAsString, Encoding.UTF8, "application/json");
var respone = await client.PostAsync("https://localhost:5003/Login/SignUp", content);
var resultStr = await respone.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SignUpResponse>(resultStr);
Console.WriteLine($"response = {result.Token}");

With HttpClient, you have to use a JSON serializer like Newtonsoft.Json, not to mention that the code looks way worse in comparison.

By the way, RestSharp doesn’t have a dependency on other libraries. This means you don’t have to worry about version conflicts with Newtonsoft.Json and alike.

Find RestSharp on NuGet Gallery

7. Polly

Polly is a wonderful fault-handling factory. It allows you to create policies on how to handle your faults. Do you want to retry three times? No problem. Do you want to add to a particular queue after something fails exactly 17 times? You can do that as well. If you want different behaviors for different errors, that’s possible. Here’s a simple example:

// Retry multiple times, calling an action on each retry  
// with the current exception and retry count 
Policy 
    .Handle() 
    .Retry(3, onRetry: (exception, retryCount) => 
    { 
        // Add logic to be executed before each retry, such as logging 
    });
Find Polly on NuGet Gallery

8. protobuf-net

When we talk about serialization, we are usually thinking about JSON or XML. But neither of those are going to be the best performing serialization by a longshot. The most performant serialization is going to be binary. Something completely incomprehensible by humans. protobuf-net is exactly that—an extremely fast binary serializer. If you’re familiar with gRPC, then you probably know that it uses protobuf under the hood. That’s not the only use case, though. There are many scenarios when you might want a fast serialization protocol. Note that without gRPC and their .proto files, protobuf will be pretty hard for versioning. You won’t be able to easily add or remove properties from your serialized objects and have the same API support different versions. Other alternatives for fast binary serializations are FlatBuffers and MessagePack. MessagePack, for example, does support schema changes and allows versioning support. Flatbuffers has other advantages, like direct access to a part of the serialization without unpacking everything.

Find protobuf-net on NuGet Gallery

NuGet packages worth a special mention

There are many more popular NuGet packages. I couldn’t mention everything, but here are some that you should probably be familiar with:
  • Json – The most popular community NuGet package of all times. It was even included automatically in some older versions of ASP.NET. But because of various reasons (performance, version conflicts), Microsoft made the switch to System.Text.Json, which is the default JSON serializer in the latest versions of ASP.NET Core.
  • Logging packages – Some of the most popular NuGet packages are logging frameworks. These include Serilog, NLog, log4net, and Extensions.Logging.
  • Queues – Queuing frameworks are extremely powerful, and most applications make use of some queue technology or other. Some of them are Kafka, Azure Queue, and RabbitMQ.
  • Unit test frameworks – Also very useful to know both testing frameworks and mocking frameworks. The first include xunit, NUnit. The latter includes Moq and FakeItEasy.
  • Caching is an integral part of modern applications. In this regard, Redis is worth knowing.

Ozcode Visual Studio Extension

Elevate LINQ debugging with visibility, clarity and insights into your queries.

Time travel to see how your code will execute before you step through it.

Heads-up display gives you powerful visualizations so you can instantly understand what’s happening in your code.

Data tips provide deep insights into your data letting you drill down to any level in a data object.

Enhance Visual Studio Debugging - Ozcode

Omer Raviv

Comments

Keep your code in good shape!

Subscribe to our blog and follow the latest news in the .NET debugging industry

Ready to Dive into Your Prod Code?

Easy debugging with full time-travel data

The Exception

A Quarterly Roundup

Subscribe to our quarterly newsletter and hear all about what’s happening around debugging with Ozcode

Share on facebook
Share on twitter
Share on linkedin
Share on email

Recent Posts

Follow Us

Join Ozcode YouTube Channel

Let’s start debugging, it’s free!

Thanks for downloading the OzCode trial!

You’re well on your way to making C# even sharper.

If your download doesn’t start automatically , please use this direct link.

If you’d like to install OzCode but don’t have
administrative privileges on your machine, please contact us.

Get Started for FREE!

Ozcode Logo

This website uses cookies to ensure you get the best experience on our website.