.Net Core Best Practices
Last Updated on
Jul 11, 2023
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 .NET Core.
.NET Core is an open-source, free, fast, lightweight and cross-platform web development system that is created and handled by Microsoft. It runs on Windows, Linux, and MAC operating systems. Though it is not an updated version of .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 .NET Web API and .NET MVC. Speed is a key feature of the .NET Core so that it is optimized for better performance. 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.
Top 18 .NET Core Best Practices
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
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.
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.
Comments