.NET Core Best Practices

.NET Core Best Practices

Load time is one of the key characteristics that reveal a site’s success when it comes to the performance of a website or an application. As a result, if it takes more than 3 seconds to load, customers may abandon the site and never return. And it is for this reason that businesses prefer to have a perfect and robust web app. One of the best technologies for this is .NET Core.

Microsoft created and maintains .NET Core, an open-source, free, fast, lightweight, and cross-platform web development system. It is compatible with Windows, Linux, and MAC operating systems. Despite the fact that it is not an updated version of .NET, it allows developers to easily control normal program flow. It is a completely redesigned version that includes a single programming model of .NET Web API and .NET MVC. The .NET Core is designed with speed in mind, and it is optimized for maximum performance. To learn more about this technology and how it can help improve application performance, let’s go over the best .NET core practices selected by our .NET development team.

Here are some of the best .NET Core practices to help developers translate their clients’ business logic into reality.

1. Inline methods

By passing arguments, reducing jumps, and restoring registers, inline methods improve app performance. Remember that the JIT (just-in-time) compiler will not inline one method that contains a throw statement. To fix it, create a static helper process that includes a throw statement.

2. Use Asynchronous Programming : (ASYNC – AWAIT)

Asp.Net Core uses the same Asynchronous programming approach to make an application more dependable, faster, and interactive. End-to-end asynchronous programming should be used in our code.

Don’t do this:

public class BadStreamReaderController : Controller
 {
  [HttpGet("/home")]
  public ActionResult<HomeData> Get()
     {
         var json = new StreamReader(Request.Body).ReadToEnd();
         return JsonSerializer.Deserialize<HomeData>(json);
     }
 }

Do this:

public class GoodStreamReaderController : Controller
 {
    [HttpGet("/home")]
    public async Task<ActionResult<HomeData>> Get()
     {
         var json = await new StreamReader(Request.Body).ReadToEndAsync();
         return JsonSerializer.Deserialize<HomeData>(json);
     }
 }

3. Optimize Data Access

To boost the application’s performance by optimizing its data access logic. Most applications are completely reliant on a database, and they must retrieve data from it, process it, and display it.

Suggestions:

  • Call all data access through the APIs asynchronously.
  • Do not get data that is not required in advance.
  • When retrieving data for read-only reasons in Entity Framework Core, use non-tracking queries.
  • Try to use aggregate and filter LINQ queries like with Where, Select, or Sum statement, so that filter thing can be performed by the database.

4. Always Use Cache

Caching is a popular and well-proven method of improving performance. Any data that is relatively stable should be cached. Response caching middleware support is provided by ASP.NET Core, which we can use to enforce response caching. Response caching can be used to improve output caching, and it can cache web server responses by adding cache-related headers to HTTP response objects. Caching large objects also saves money on allocations.

Caching technique:

  • In-memory caching
  • Distributed cache
  • Cache tag helper
  • Distributed cache tag helper

A memory cache can be used or a distributed cache like NCache or Redis Cache can be used.

5. Response Caching Middleware Components

If the response data is cacheable, this response caching middleware monitors, stores, and serves the responses from the response cache. Microsoft has access to this middleware. AspNetCore. Package ResponseCaching.

public void ConfigureServices(IServiceCollection services)
 {
     services.AddResponseCaching();
     services.AddRazorPages();
 }

6. Enable Compression

We can improve application performance by reducing response size because it transfers less data between the server and client. You can take advantage of response compression in ASP.NET Core to reduce bandwidth requirements and response time. It serves as a sure-shot middleware component in ASP.NET Core.

public void ConfigureServices(IServiceCollection services_collection)
 {
         services_collection.AddResponseCompression();
         services_collection.Configure<GzipCompressionProviderOptions>
         (opt =>
         {
             opt.Level = CompressionLevel.Fastest;
         });
 }

7. Bundling and Minification

We can reduce the number of server trips by doing so. Try to upload all client-side assets, such as styles and JS/CSS, at once. You can use minification to first minify your files before bundling them into a single file that loads faster and reduces the number of HTTP requests.

8. Use Content Delivery Network (CDN)

Despite the fact that the speed of light exceeds 299000 km/s, which is extremely fast, it also aids us in keeping our data close to our customers. It is simple to load on the server if there are only numbered CSS and JS files. Consider using a CDN for larger static files. Most CDNs have multiple locations and serve files from a local server. Loading files from a local server can improve website performance.

9. Load JavaScript from the Bottom

We should always try to load our JS files at the end, unless they are required earlier. As a result, your website will load faster, and users will not have to wait as long to see the information.

10. Cache Pages or Cache Parts of Pages

Instead of querying the database and re-rendering a complex page, we could save it to a cache and use that data to serve subsequent requests.

[OutputCache(Duration=20, VaryByParam="none")]
 Public ActionResult HomeIndex() {
         return View();
 }

11. Use Exceptions only When Necessary

Exceptions should be uncommon. In comparison to other code flow patterns, the catch and throw of exceptions is slow. Exceptions are not used to control the program’s flow. Consider the program’s logic when identifying and resolving exception-prone scenarios.

Exceptions should be thrown or caught for unusual or unexpected circumstances. App diagnostic tools, such as Application Insights, can be used to identify common exceptions in an app and how they perform.

12. Setting at Environment Level

We must use the development environment when developing our application, and the production environment when publishing it. The configuration for each environment is different with this, and it is always the best practice.

When we use .NET Core, it is extremely simple. Our project folder contains the appsettings.json file. The appsettings are visible. Development.json is a file that contains the development environment and appsettings. If we extend it, we’ll need a Production.json file for the production environment.

13. Routing

We can provide detailed names, and we should use NOUNS instead of VERBS for the routes/endpoints.

Don’t do this:

[Route("api/route-employee")]
 public class EmployeeController : Controller
 {
         [HttpGet("get-all-employees")]
         public IActionResult GetAllEmployees() { }
  
        [HttpGet("get-employee-by-Id/{id}"]
         public IActionResult GetEmployeeById(int id) { }
 }

Do this:

[Route("api/employee")]
 public class EmployeeController : Controller
 {
     [HttpGet]
     public IActionResult GetAllEmployees() { }
  
    [HttpGet("{id}"]
     public IActionResult GetEmployeeById(int id) { }
 }

14. Use AutoMapper to Avoid Writing Boilerplate Code

AutoMapper is a convention-based object-to-object mapper with minimal configuration requirements. Basically, when we want to separate domain models from view models.

We can map domain models and view models like this after configuring AutoMapper.

public class EmployeeService
 {
    private EmployeeRepository employeeRepository = new EmployeeRepository();
 
    public EmployeetDTO GetEmployee(int employeeId)
     {
         var emp = employeeRepository.GetEmployee(employeeId);
         return Mapper.Map<EmployeeDTO>(emp);
     }
 }

15. Use Swagger

Swagger is a RESTful API representation that allows for interactive documentation, discoverability, and the generation of Client SDK support.

It usually only takes a few minutes to set up a Swagger tool. We get a fantastic tool for documenting our API.

16. Logging

When we keep a consistent, fixed logging format, this is referred to as structured logging. Logs can be easily filtered, navigated, and analyzed using structured logs.

Asp.Net Core includes structured logs by default, and the Asp.Net team will need to make it consistent in order to keep the entire code consistent. The application communicates with the web server. Serilog is a great logging framework that you can use for logging.

17. Do Refactoring for Auto-generated Code

In .NET Core, there are a lot of auto-generated codes, so set aside some time to examine the logic flow, and because we know our application better, we can improve it a little.

18.Delete Unused Profiles

  • Delete unused custom middleware components from startup.cs
  • Remove any default controllers you aren’t using.
  • Trace and remove all redundant comments used for testing from the views.
  • Remove the unwanted white spaces as well

Share this post

Leave a Reply