×

Asp.Net Core Application Best Practices

Debasis Saha  Print   11 min read  
14 May 2022
 
Intermediate
407 Views

Introduction

In the time of development of a website or any web-based application, load time is always considered one of the critical points related to the success of the application or site. If the website or application takes more than 3 seconds to load, there is always a chance that the customer may leave the site or application and not use it. For this reason, we always want to create the perfect and robust application. For this purpose, ASP.Net Core is the best framework to achieve the goal.

Why Use ASP.Net Core

ASP.Net Core is an open-source, lightweight, fast, and cross-platform framework that is a re-write of the Asp.Net Framework handled and created by Microsoft. Since it is not an updated version of ASP.Net, it helps developers control normal program flow with ease. It is a redesigned version from scratch and provides a single programming model of ASP.NET Web API and ASP.NET MVC. Speed is one of the critical features of the ASP.NET Core since it is mainly optimized for better and speedy performance.

There is some reason behind using ASP.NET Core for any web-based applications –

  • We can develop any web application and services, IoT-based applications, and backend services related to the mobile application using the ASP.NET Core framework.
  • Since it is an open-source framework, the developed application can be used in any operating system like Windows, macOS, and Linux.
  • We can deploy the developed application on either cloud or on-premises servers.

Advantages of Asp.Net Core

Some of the significant advantages of the .NET Core framework are –

  • NET is a lightweight, fast, and high-performance web application framework to boost the application's performance.
  • .NET Core-based application can be hosted on any environment like Apache, IIS, Docker, or Self Hosting model.
  • In .NET Core, we can take advantage of built-in dependency injection.
  • NET Core framework supports modern, client-side-based frameworks like Angular, ReactJs, React with Redux, etc.
  • We can take the benefits of modular HTTP requests in this framework.

Best practice in .Net Core Regarding Code Performance

So, now we will discuss the best coding practices related to the ASP.NET Core, which can be helpful for developers to develop code using this framework to achieve optimum performance.

Inline Methods

To improve the application's performance, you need to use the Inline methods by passing arguments and reducing jumps. We need to remember that the technique containing a throw statement by the JIT(just-in-time) compiler is not inline. We need to use a static help process that encompasses all the throw statements to solve it.

Use Async Methods (async-await)

If we want to make the application much more dependable, faster, and interactive, Asp.Net Core always leverages the Asynchronous programming approach. For our applications, we need to implement end-to-end asynchronous programming. For example,

Wrong Approach
 
public class StreamReaderController : Controller
{ 
 [HttpGet("/home")] 
 public ActionResult Get()
 { 
 var json = new StreamReader(Request.Body).ReadToEnd(); 
 return JsonSerializer.Deserialize(json); 
 } 
}
Correct Approach
 
public class StreamReaderAsyncController : Controller 
{ 
 [HttpGet("/home")] 
 public async Task> Get() 
 { 
 var json = await new StreamReader(Request.Body).ReadToEndAsync(); 
 return JsonSerializer.Deserialize(json); 
 } 
}

Optimize DAL Layer

We always need to optimize the DAL Layer to improve the performance of the applications. Most of the applications are always dependent on the database, and they have to fetch the data from the database, process data, and display it on the application after that. For this type of application, we can follow the below suggestions –

  • Fetch the data from the database through the asynchronous APIs methods.
  • Do not fetch any data which are not required
  • When we fetch the data only for display purposes in Entity Framework Core, use the non-tracking queries.
  • Use aggregate and filter LINQ queries like Select, Where, Sum, or Average commands. In this way, we can perform the filters in the database section.

Use the caching techniques

Caching is one of the best and most tested ways to improve the applications' performance. We can use cache to store any data which is relatively stable. Asp.Net Core provides response caching middleware support, which we can use to implement response caching. With the help of response caching, we can cached web server responses using cache-related headers to the HTTP response objects. Also, we can cache large data objects to avoid costly transactions. Some of the caching techniques which can be used in Asp.Net Core –

  • In-Memory Caching
  • Distributed caching
  • Cache Tag Helper
  • Distributed Cache Tag helper

Response Caching Middleware

In Asp.Net Core, we can use response caching middleware to cache the response data so that the caching application will pick up the data from the response cache. This approach improves the performance of the applications. The response cache middle is available to Microsoft.AspNetCore.Response Caching package.

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

Compression

If we can reduce the response size, the actual performance of the application will increase. Because in this way, less amount data is transferred between the server and the client. With the help of response compression functionality in Asp.Net Core, we can reduce the response data size, and in this way, the bandwidth requirements decreased due to the lower response size. In Asp.Net Core, it acts as middleware components.

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

Load JavaScript Files at the End

If we use JavaScript files in the web application, we need to load our JavaScript Files at the end if not require In this way, web applications load faster, and users will not have to wait long to see the information.

Use Exception only when Required

In the application, we need to implement Exception's logic whenever it is required. Because the catch and the throw of exceptions are pretty slow compared to the other code flow patterns, we can use App diagnostic tools like Application Insights to identify common abnormalities in the application.

Routing

In the route, we need to provide the detail's name, and also, we need to use Nouns in place of Verbs for the route key/endpoints.

Wrong Approach –
 
[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) { }
}
Correct Approach –
[Route("api/employee")] 
public class EmployeeController : Controller
{ 
 [HttpGet]
 public IActionResult GetAllEmployee() { }
 
 [HttpGet("{id}"]
 public IActionResult GetEmployeeById(int id) { }
}

Use AutoMapper

We need to use AutoMapper Functionality to avoid writing boilerplate code. AutoMapper is always a convention-based object-to-object mapper which requires a minimal configuration. It is much more important when we want the physical separation between the domain and view models. To configure the AutoMapper, we can map the domain model and the view model just like below –

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

Logging

In the application, we can implement the logging system. Structured Logging is always better to keep the design consistent and provides a fixed logging format. With the help of structured logs, we can easily filter the log data, navigate, and analyze the logs if required. Asp.Net Core provides the structured logs by default and keeps the entire code consistent. Serial Log, NLog, etc., are some of the excellent logging frameworks used in web applications.

Use Refactoring for Auto-Generated Code:

.Net Core Framework generates lots of code as an auto-generated process. Sometimes we need to examine the logic flow, as we have much better functional knowledge of our application. So, we can improve the code a little bit.

Best practice in ASP.Net Core Regarding Security

Asp.net Core is always considered as one of the most secure framework platforms. But still, we need to monitor the activity in our application and always try to follow the best practices related to the .Net Core framework security practices.

  • Cross-Site Scripting (XSS):- Cross-Site Scripting attack is a common issue for web applications. To protect the applications from this type of attack, always use the regular expression on both the client-side and server-side. In addition, it is always a best practice to store any validated data into the database and always use HTML encryption with Razor to handle those scripts.
  • Cross-Site Request Forgery (CSRF): Cross-site Request Forgery or CSRF is one of the major attacks occurred when we visit a malicious website, and then that particular website sends a request to an application site on behalf of us. To prevent or block this attack, we must use anti-forgery token Anti Forgery Token() before the controller action. In this process, the server sends a token to the user, and after the user makes a request, it sends the token back to the server for verification of the request. Tokens can be saved both in the header and in the cookie.
  • Use SSL and HTTPS: - SSL means Secure Sockets Layer. This process establishes secure or encrypted connections between the client and server. With the help of SSL, the requests and responses passed between the client and the server will be encrypted for data integrity. We can also implement HTTPS (Hypertext Transfer Protocol Secure) to protect the applications.
  • SQL Injection: - SQL Injection is one of the most common threats for any web-based application. For these types of attacks, Hackers mainly used SQL Injections. So, in the application, if we use the following principles or technologies where code doesn't directly depend on the SQL Queries, then automatically threat minimizes. This approach, like Entity Framework Core, parameterized queries, validating the inputs on the server-side, and using stored procedures will always help the application minimize the thread.
  • Use Updated Versions of Framework: - While working on the application, always try to use the latest libraries and framework version. This way, we can prevent the blockers from using their well-known vulnerabilities.
  • Always use Secure Login: - Sometimes, the web application has its authentication module to validate users. So, we always need to be very careful while developing this type of code. For example, suppose we forgot to remove the authentication cookies after successful logout. In that case, it will help the attackers to steal user credentials such as cookies and session values, and then attackers can access the entire application. Also, we always need to implement complex login credentials, and if possible, we can implement the .NET Core Identity features to authenticate the users.
  • XML External Entity (XXE): - XML External Entity or XXE can perform a denial-of-service attack by injecting entities within the entities. It affects the increase of server's utilization, and byways server can be shutdown. To protect our application from these attacks, we need to implement XmlTextReader to parse XML files and then set the DtdProcessing property as Prohibit or Ignore.
  • Clear Cookies: - We user logged out from the application, we need to remove the related cookies or session objects generated by the application from the browser automatically. Otherwise, hackers can use this information and can perform an unauthorized login. It is usually known as a Session Fixation attack.
  • Hide version: - While HTTP Response is sent from the server to the client, that response always contains the information related to the application. So, we must protect and remove the Version-related information from the end-users. If hackers find the exact version of the application, they can attack it with version-specific disclosed vulnerability. So, always try to remove X-Powered-By from the response header part of the application.
  • Audit Trails and Logging Analyze: -Audit and Logging system always provides information related to unusual situations to the Administrator. It also helps monitor the application's health status. Sometimes, the development team also puts some vital information when analyzing the issues or defects highlighted by the end-users.
Conclusion

So, after the .NET 6, we can achieve much faster performance and smoother web-based applications. This article discusses performance improvement in terms of process, coding, and data. These steps or techniques will help us make our application faster to get a better experience.

Share Article

Take our free skill tests to evaluate your skill!

In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.

Learn to Crack Your Technical Interview

Accept cookies & close this