Tuesday 12 April 2022

ASP.NET Core - Best practices (tips and tricks)

 Hello friends,

 In this article, I will explain what are the best practices when we use the .NET core

We will talk about some of the best practices with tips and tricks while working with ASP.NET Core. 

Here are some of the best .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


 Happy programming!!

Don’t forget to leave your feedback and comments below!

Regards

Sujeet Bhujbal

--------------------------------------------------------------------------------

 Blog: www.sujeetbhujbal.com

Personal Website :-http://sujeetbhujbal.wordpress.com/ 

CodeProject:-http://www.codeproject.com/Members/Sujit-Bhujbal 

CsharpCorner:-http://www.c-sharpcorner.com/Authors/sujit9923/sujit-bhujbal.aspx

Linkedin :-http://in.linkedin.com/in/sujitbhujbal 

Twitter :-http://twitter.com/SujeetBhujbal 

------------------------------------------------------------------------------

No comments:

Post a Comment