Tuesday 23 May 2023

How to implement global exception handling in .NET Core

  Hello friends,

 In this article, I will explain What is global exception and Pros and cons of global exception and  

  • How to implement it via middleware’s


Introduction of Global Exception

We often come up with exceptions in our application and we have two ways in general to handle that exception.

  • Handle at controller/service level everywhere in the application
  • Handle from one place and control the application

 

Pros and Cons of Global Exception

Let’s see the pros and cons of this approach

Pros  :

  • Code becomes easy to manage because we don’t need to look into n different try-catch blocks, just look from one place and deal with them.
  • More readable because a few lines of code managing the whole exceptions of the application
  • Removes repeated code (try-catch everywhere)
  • It gives us more control so we can catch exceptions and return responses of our own type, in most cases we return Internal Server Error.  

Cons :

  • A global exception handler can make it harder because sometimes it will catch the exception at a broad level and deal with it accordingly without digging down to the exact lower-level exception

If you are on short time and you need to implement exception handling then global exception handling is the best solution.


How to Implement it via Middleware

We have different ways to implement global exception handling in our .NET application e.g. using custom/built-in exception filter or creating our custom middleware using IMiddleware and implementing its methods.

So every time before and after controller request will come in this middleware and we would add a try-catch block here and the request would be caught here.

Step 1: Create Middleware




If you are worried about what is JsonConvert.SerializeObject(response) then check post on ‘Serialization’.


Step 2 : Register the Middleware as a Service and then use it in Middleware in Program.cs



That’s all you need to do. Now you can add any exception by throwing a new Exception("This is a test exception"), and test if it works or not


 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 

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



 

Monday 8 August 2022

How to prevent 𝐂𝐫𝐨𝐬𝐬 𝐒𝐢𝐭𝐞 𝐒𝐜𝐫𝐢𝐩𝐭𝐢𝐧𝐠 (𝐗𝐒𝐒) 𝐚𝐭𝐭𝐚𝐜𝐤𝐬 in Asp.Net Core

Hello friends,

 In this article, I will explain What is Cross-Site Scripting (XSS) attacks and how to prevent -Site Scripting (XSS) attacks


 What is Cross-Site Scripting (XSS) attacks 

    Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites.

XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser-side script, to a different end user.

    Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

    An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site.

 

How to Protect Yourself

The primary defenses against XSS are described in the OWASP XSS Prevention Cheat Sheet.

Also, it’s crucial that you turn off HTTP TRACE support on all web servers. An attacker can steal cookie data via Javascript even when document.cookie is disabled or not supported by the client.

This attack is mounted when a user posts a malicious script to a forum so when another user clicks the link, an asynchronous HTTP Trace call is triggered which collects the user’s cookie information from the server, and then sends it over to another malicious server that collects the cookie information so the attacker can mount a session hijack attack.

This is easily mitigated by removing support for HTTP TRACE on all web servers.

 

 

How to Prevent XSS -  

To keep yourself safe from XSS, you must sanitize your input. Your application code should never output data received as input directly to the browser without checking it for malicious code.

One of the steps in the process is to use the 𝐗-𝐗𝐒𝐒-𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐢𝐨𝐧.
X-XSS-Protection is a header that can be set on a webpage to activate “limited” XSS protection in certain browsers.

 

1.    X-XSS-Protection: 1 : Force XSS protection (useful if XSS protection was disabled by the user)

2.    X-XSS-Protection: 0 : Disable XSS protection

3.    The token mode=block will prevent browser (IE8+ and Webkit browsers) to render pages (instead of sanitizing) if a potential XSS attack is detected.

 



Syntax
:

 

𝐗-𝐗𝐒𝐒-𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐢𝐨𝐧: 1; 𝐦𝐨𝐝𝐞=𝐛𝐥𝐨𝐜𝐤

- This enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

Please Note: Some of the popular browsers like chrome, edge have changed their policy of implementing XSS protection. This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead - we will talk about that in the next post.

 

 

Example:

 



  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 

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

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 

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