add

Wednesday, January 8, 2025

Proper order is adding middleware in dot net core application

 Proper order is adding middleware in dot net core application

Introduction

When developing a web application in .NET Core, the middleware pipeline plays a crucial role in handling HTTP requests and responses. Understanding the correct order in which to arrange middleware components is essential for ensuring that your application functions as intended. The sequence of middleware dictates how requests are processed and how responses are generated, which can affect performance, security, and overall behavior. In this guide, we will explore the principles and best practices for organizing middleware in the .NET Core environment, helping you to create robust and efficient applications.


Tuesday, January 7, 2025

Adding custom middleware in Dot Net Core application

 

Adding custom middleware in Dot Net Core application

 

Introduction

In ASP.NET Core, middleware plays a crucial role in request processing pipelines, acting as a conduit through which HTTP requests flow before reaching the destination.

By integrating a custom middleware class into your application, you gain the flexibility to intercept, modify, or handle requests and responses according to your specific requirements. This powerful feature allows developers to inject custom logic at various stages of request processing, thereby enhancing functionality, improving security, and optimizing performance.

This introduction will guide you through the process of implementing custom middleware in the Program.cs file of a .NET Core application, showcasing practical examples and best practices.

 

Steps of adding the custom middleware

Create a Custom Middleware Class:

  • Create a new class file, for example MyCustomMiddleware.cs.


Inherit the class with an interface IMiddleware and implement the interface’s methods.



·         Change the code of the method InvokeAsync with the custom code



Note: The MyCustomMiddleware in this example is inside a folder named ‘CustomMiddleWare’ hence the namespace is showing as app1.CustomMiddleWare (my application name is app1)

Adding the custom middleware in the pipeline:

·         Add the namespace in Program.cs

·         Add the custom middleware class using AddTransient method just after the var builder line as shown below:



 

Note : the line of adding the custom middleware should be before the builder.Build() command.

·         In order to call the custom middleware class, add a line

app.UseMiddleware<MyCustomMiddleware>();

 



 Conclusion

By incorporating custom middleware into your ASP.NET Core application, you harness the power to tailor the request-handling pipeline to your specific requirements. This enables you to inject custom logic, enhance security measures, and optimize performance throughout the request-processing flow.



 

 The modular nature of middleware promotes cleaner code and better maintainability, allowing for the seamless addition of new functionality without disrupting existing components. By understanding and utilizing custom middleware, developers can build more robust, flexible, and efficient applications, ultimately delivering superior user experience. Happy coding!

Saturday, February 24, 2024

How to generate table Model class from SQL Server using EntityFramework Core

You may get into a situation where you have an existing SQL Server, and you want to build a code first DB approach using Entity Framework core.


You can use Scaffold-DbContext to create a model based on the existing database. 

Below are the parameters that can be specified with Scaffold-DbContext in Package Manager Console:

Scaffold-DbContext [-Connection] [-Provider] [-OutputDir] [-Context] [-Schemas>] [-Tables>] 
                    [-DataAnnotations] [-Force] [-Project] [-StartupProject] [<CommonParameters>]

In Visual Studio, select menu Tools --> NuGet Package Manger --> Package Manger Console and run the following command:

Scaffold-DbContext "Server=.\SQLExpress;Database=SchoolDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

If you get an error like : 

A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.

add attribute : TrustServerCertificate=True to the command. So your final command will look like:

Scaffold-DbContext "Server=servername\instaneName;Database=dbName;user id=userID;password=passwordValue;TrustServerCertificate=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models


Saturday, September 16, 2023

ERROR : Only the invariant culture is supported in globalization-invariant mode.

 Hi All,


While working with dot net core, if you encounter the following error:

Only the invariant culture is supported in globalization-invariant mode. 

See https://aka.ms/GlobalizationInvariantMode for more information. (Parameter 'name')

en-us is an invalid culture identifier.


Here is the simple solution to resolve this:

1. Right click the dot net core project --> Select Edit Project File

2. In the XML file, file the node : 

    <InvariantGlobalization>true</InvariantGlobalization>

3. Replace 'true' with 'false'

The line should be :

    <InvariantGlobalization>false</InvariantGlobalization>

4. Save the project file.

5. Build the project and check for error.

There will be no error on the globalization.

Cheers :) 

Friday, September 15, 2023

.NET 8 preview not showing in Visual Studio 2022

 Have you faced an issue where .Net 8 version framework is not available to select while creating a new .Net core project?


Steps to check:

  1. Check whether you have installed the latest preview of Visual Studio 2022 (17.7).
  2. Enable Preview feature usage:
    1. Visual Studio --> Go to 'Tools' --> 'Manage Preview Features'
    2. Ensure you have 'Preview Feature' selected.
    3. Scroll down and on the right you will see an option 'Use Preview of the .Net SDK'
    4. Select the option. Click 'Ok' and restart the Visual Studio
    5. Now you will have the .Net 8 Preview SDK listed.









Thursday, September 14, 2023

A connection was successfully established with the server, but then an error occurred during the login process.

 If you are creating the database using code first db approach using Entityframework Core and while creating the database using 'Update Database' command encounter the below error:


A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)

Chances are there that there is an issue with the connection string mentioned in the web.config or appsettings.json (if using asp.net core app).

Compare the below before and after connection string :

OLD:

data source=YOUR_SERVER_NAME;initial catalog=YOUR_DB_NAME;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework


NEW:

data source=YOUR_SERVER_NAME;initial catalog=YOUR_DB_NAME;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework;Trusted_Connection=SSPI;Encrypt=false;


Add the above highlighted part at the end of the connection string and try to build the database.

It should work.

Cheers :) 

Tuesday, November 1, 2011

Convert DATETIME TO TIMESPAN IN C#

In the previous post, I mentioned how to convert DATETIME to TIMESPAN. Now if the requirement is to convert DATETIME TO TIMESPAN, we can do that in one line: DateTime dt="XXX"; TimeSpan TS = new TimeSpan(dt.Now.Ticks); This will convert the DateTime to TimeSPan. Varun