.NET Core Best Practices
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +28K Followers | Now Hiring!
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:
C#
1
public class BadStreamReaderController : Controller
2
{
3
[HttpGet("/home")]
4
public ActionResult<HomeData> Get()
5
{
6
var json = new StreamReader(Request.Body).ReadToEnd();
7
return JsonSerializer.Deserialize<HomeData>(json);
8
}
9
}
Do this:
C#
1
public class GoodStreamReaderController : Controller
2
{
3
[HttpGet("/home")]
4
public async Task<ActionResult<HomeData>> Get()
5
{
6
var json = await new StreamReader(Request.Body).ReadToEndAsync();
7
return JsonSerializer.Deserialize<HomeData>(json);
8
}
9
}
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:
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:
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.
C#
1
public void ConfigureServices(IServiceCollection services)
2
{
3
services.AddResponseCaching();
4
services.AddRazorPages();
5
}
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.
C#
1
public void ConfigureServices(IServiceCollection services_collection)
2
{
3
services_collection.AddResponseCompression();
4
services_collection.Configure<GzipCompressionProviderOptions>
5
(opt =>
6
{
7
opt.Level = CompressionLevel.Fastest;
8
});
9
}
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.
C#
1
[OutputCache(Duration=20, VaryByParam="none")]
2
Public ActionResult HomeIndex() {
3
return View();
4
}
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 practise.
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:
C#
1
[Route("api/route-employee")]
2
public class EmployeeController : Controller
3
{
4
[HttpGet("get-all-employees")]
5
public IActionResult GetAllEmployees() { }
6
7
[HttpGet("get-employee-by-Id/{id}"]
8
public IActionResult GetEmployeeById(int id) { }
9
}
Do this:
C#
1
[Route("api/employee")]
2
public class EmployeeController : Controller
3
{
4
[HttpGet]
5
public IActionResult GetAllEmployees() { }
6
7
[HttpGet("{id}"]
8
public IActionResult GetEmployeeById(int id) { }
9
}
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.
C#
1
public class EmployeeService
2
{
3
private EmployeeRepository employeeRepository = new EmployeeRepository();
4
5
public EmployeetDTO GetEmployee(int employeeId)
6
{
7
var emp = employeeRepository.GetEmployee(employeeId);
8
return Mapper.Map<EmployeeDTO>(emp);
9
}
10
}
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 analysed 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