.net core best practices

Whenever it comes to the performance of a website or an application, load time is one of the key characteristics that unveil the success of a site. So, if it takes more than 3 seconds to load, there are chances that the customers might leave the site and never come back. And this is why businesses prefer to have a perfect and robust web app. For this, one of the best technologies is ASP.Net Core.

ASP.Net Core is an open-source, free, and cross-platform web development system that is created and handled by Microsoft. Though it is not an updated version of ASP.NET, it enables the developers to control normal program flow with ease. It is redesigned version from scratch and also comes with a single programming model of ASP.NET Web API and ASP.NET MVC. To know more about this technology and the ways it helps in boosting the performance of the application, let’s go through the best practices of .net core handpicked by our .net development team.

What is ASP.NET Core?

ASP.Net Core is an open-source, fast, lightweight, cross-platform, and re-write of the Asp.Net framework which runs on Windows, Linux, and Mac operating systems. Speed is a key feature of the ASP.Net core so that it is optimized for better performance.

Why Use ASP.NET Core?

  • You can build any web application and services, IoT app development, and mobile backend development services.
  • Works on any development tools like Windows, Mac OS-X, and Linux.
  • You can deploy the applications on cloud and on-premise cloud
  • It can be easily executed on the .NET core.

To improve application performance it is good to ensure that we build applications that use a fewer amount of resources to generate the desired output. This post presents one of the best practices to improve the performance of .Net core applications.

Advantages of ASP.NET Core

Some of the major advantages of .Net Core are –

  • ASP.Net is a fast, lightweight, and high-performance web framework that can boost the core performance of the application.
  • .Net core has the hosting capability which enables the developers to host the app on Apache, IIS, Docker, or Self Hosting.
  • It supports built-in dependency injection.
  • .Net Core is an open-source framework and being community-focused it offers perfect performance profiling tools.
  • ASP.NET Core is a framework that supports modern, client-side frameworks like ReactJs, AngularJs, and React with Redux, etc.
  • The .Net Core performance gets boosted with the help of side-by-side app versioning, as it supports the simultaneous running of various versions of applications.
  • This framework is a cross-platform that can run frequently called code paths & applications on development and app diagnostic tools that support Linux, Windows, and Mac.
  • It supports modular HTTP requests.

Top 18 .NET Core Best Practices

Here are some of the best ASP.Net Core practices that can help developers to bring down the business logic of their clients into reality.

1. Inline methods

Inline methods improve app performance by passing arguments, reducing jumps, and restoring registers. Remember, one method containing a throw statement by the JIT (just-in-time) compiler will not be inline. To resolve it, use a static helper process that encompasses a throw statement.

2. Use Asynchronous Programming : (ASYNC – AWAIT)

To make an application more dependable, faster, and interactive, Asp.Net Core leverages the same Asynchronous programming approach. In our code, we should employ end-to-end asynchronous programming.

For an example:

Don’t:

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

Do:

public class CorrectStreamReaderController : 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 improve the performance of the application by optimizing its data access logic. Most applications are fully dependent on a database and they have to get data from the database, 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 one of the popular and proven ways of improving performance. We should cache to store any data that is relatively stable. Asp.NET Core offers response caching middleware support, which we can use to enforce response caching. We can use response caching to improve output caching and It can cache web server responses using cache-related headers to the HTTP response objects. Also, Caching large objects avoids costly 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 response data is cacheable, this response caching middleware monitors and stores responses and serves them from the response cache. This middleware is available to Microsoft.AspNetCore.ResponseCaching package.

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

6. Enable Compression

By reducing response size we can improve the performance of the application because it transfers less data between the server and client. You can take the benefits of response compression in ASP.Net Core to reduce the requirements of bandwidth and lower the response. In ASP.Net Core it acts as sure-shot middleware components.

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

7. Bundling and Minification

Using this we can reduce the number of server trips. Try to upload all client-side assets at once, such as styles and JS/CSS. Using minification, you can first minify your files and then bundle them into one file that loads faster and decreases the number of HTTP requests.

8. Use Content Delivery Network (CDN)

Despite the fact that the speed of light is more than 299000 km/s, which is extremely fast, it also helps us keep our data near to our consumers. If there are only numbered CSS and JS files then it is easy to load on the server For bigger static files, you can think of using CDN. The majority of CDNs have many locations and serve files from a local server. The website performance can be enhanced by loading files from a local server.

9. Load JavaScript from the Bottom

Unless they are required earlier, we should always strive to load our JS files at the end. Your website will load faster as a result, and users will not have to wait long to see the information.

10. Cache Pages or Cache Parts of Pages

Rather than considering the database and re-rendering a complex page, we could save it to a cache and use that data to serve later requests.

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

11. Use Exceptions only When Necessary

Exceptions should be rare. The catch and throw of exceptions are slow in comparison to other code flow patterns. Exceptions are not used to regulate the flow of the program. Take into account the logic of the program to identify and resolve exception-prone scenarios.

 Throw or catch exceptions for unusual or unexpected conditions. You can use App diagnostic tools like Application Insights to identify common exceptions in an app and how they perform.

12. Setting at Environment Level

When we develop our application we have to use the development environment and when we publish our application we have to use the production environment. With this, The configuration for each environment is different and it’s always the best practice.

It is extremely easy to do when we use .Net Core. The appsettings.json file can be found in our project folder. We can see the appsettings.Development.json file for the environment of the development and the appsettings.Production.json file for the environment of the production if we extend it.

13. Routing

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

Don’t:

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

Do:

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

14. Use AutoMapper to Avoid Writing Boilerplate Code

AutoMapper is a convention-based object-to-object mapper that requires little configuration. Basically, when we want separation between domain models and view models.

To configure AutoMapper and we can map domain models and view models like this.

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 representation of a RESTful API that allows interactive documentation, discoverability, and generation of Client SDK support.

Setting up a Swagger tool usually takes a couple of minutes. We get a great tool that we can use to document our API.

16. Logging

Structured logging is when we keep a consistent, fixed logging format. Using structured logs, it’s easy to filter, navigate and analyze logs.

Asp.Net Core has structured logs by default and to keep the entire code consistent, the Asp.Net team will have to make it consistent. The web server communicates with the application. Serilog is an excellent logging framework that can be used. 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

Closing Thoughts on .NET Core Application Best Practices

Undoubtedly, now the overview of .NET 6 has been released. The performance claims of a faster and smoother experience were delivered in our experience. You will observe performance improvement in terms of data that we process. It can help us process the information faster and provide a better experience. Our main goal in writing this blog was to reacquaint you with the best practices for growth and strategies for Net Core.

profile-image
Vishal Shah

Vishal Shah has an extensive understanding of multiple application development frameworks and holds an upper hand with newer trends in order to strive and thrive in the dynamic market. He has nurtured his managerial growth in both technical and business aspects and gives his expertise through his blog posts.

Related Service

Know more about ASP.Net Development Services

Learn More

Want to Hire Skilled Developers


    Comments

    • Leave a message...

    Related Articles
    .net core best practices
    Angular Best Practices and Security
    Nov 12, 2021
    .net core best practices
    ASP.NET Core and Docker
    Nov 12, 2021
    .net core best practices
    Node JS BEST PRACTICES AND SECURITY
    Nov 17, 2021