Posts

Using Cookies in ASP.NET Core apps

Image
cookies Using Cookies in ASP.NET Core apps What are cookies Cookies are small data files sent by websites that are stored in the browser Cookies are sent every time a request is sent to the server Cookies are useful for persisting user login, tracking user activity to create personalized experiences, etc. Demo We will create a simple TODO list web app using ASP.NET Core The server will save the todo list in the user’s browser using cookies Set cookie A server can set a cookie and send it in the response to the client’s browser The browser will update the cookie Each cookie has a unique key In our demo application, the server sets a cookie to store todos in the client’s browser using Response.Cookies.Append Response . Cookies . Append ( nameof ( Todo ) , JsonSerializer . Serialize ( todos ) ) ; Retrieve Cookie data Client Browser sends cookies to the server in every request The cookie data can be retrieved using Request.Cookies In our dem...

Cookie based authentication explained in ASP.NET Core

Image
cookie_auth Cookie based authentication explained in ASP.NET Core Cookie based authentication can be implemented in ASP.NET Core using the built in Authentication service and Authentication middleware Add cookie authentication service in DI container // Add Cookie Authentication service builder . Services . AddAuthentication ( CookieAuthenticationDefaults . AuthenticationScheme ) . AddCookie ( options = > { options . LoginPath = "/Account/Login" ; // Specify the path to the login page options . AccessDeniedPath = "/Account/AccessDenied" ; // Specify the path for access denied options . ExpireTimeSpan = TimeSpan . FromMinutes ( 60 ) ; // Set the cookie expiration time options . SlidingExpiration = true ; // Enable sliding expiration } ) ; AddAuthentication adds required services for authentication. It also specifies the default authentication scheme to be used for authenticati...

Create Middleware in dotnet

Image
dotnet middleware Create Middleware in dotnet What is middleware in ASP.NET A request received to a ASP.NET web application is encapsulated as a HttpContext object and the object is processed by a series of application logic (aka middleware ) in a configured sequence. This sequence of middleware in which the requst is processed is called Request Pipeline Use, Map, Run methods Use , Map and Run methods help us to configure the middleware pipeline in an ASP.NET Core application Use method appends a new middleware to the middleware pipeline // Use Middleware: Append middleware to pipeline app . Use ( async ( context , next ) = > { Console . WriteLine ( "Executing middleware before next()" ) ; await next . Invoke ( ) ; // Calling the next middleware in the pipeline Console . WriteLine ( "Executing middleware after next()" ) ; } ) ; Map method branches the middleware pipeline for a specific request pat...

.NET dependency injection explained with example

dotnet DI .NET dependency injection explained with example Dependency Injection container (DI container) Services (like email service, database service) are used generally by the application logic to interface with the external systems DI container is a collection of dependencies (aka services) Application logic can request an instance of a required service from the DI container Service Lifetimes When requesting a service instance from a DI container A new service instance is created every time if it is a Transient service A single instance of a service is reused every time if it is a Singleton service A service instance is reused through out a http request if it is a Scoped service. Scoped service is applicable only in web applications Inversion of Control for Dependency Injection While adding a service to the DI container, the service signature can be mentioned as an interface. An example is shown below. services . AddSingleton < IMyServic...

HttpContext, Dependency Injection, Request Pipeline, Middleware in ASP.NET Core web apps explained

Image
middleware_di_httpcontext_explained ASP.NET Core is a framework to build web applications that run on .NET runtime Web Application An ASP.NET Core web application contains HttpContext object (created per HTTP request) Dependency Injection container (aka DI container) Request pipeline (bunch of middlewares) HttpContext object When a web application receives a HTTP request, it creates a HttpContext object. HttpContext object contains all the HTTP related information like HTTP request, HTTP response, session details etc. All the attributes of a HttpContext object can be found in official docs here Dependency Injection container (DI container) It is a collection of classes known Services Before running the web application, services are added (aka registered) into the web application’s DI container During registration, the lifetime of a service is declared as one of Transient , Scoped , Singleton Transient - new service instance created every ...

ClaimsPrincipal, ClaimsIdentity, Claims explained in dotnet authentication

Image
claimsprincipal_dotnet Authentication means identifying a subject (user, external application etc) ASP.Net Core Identity is a framework that uses claims based authentication to authenticate users Key concepts in Claims-based authentication Claim Claim is a statement about the subject (user) being authenticated It is a key value pair (like username=John is a claim, email=john1543@gmail.com is a claim, userId=236 is a claim) A claim can have an issuer (for example: userId=236 as per system , date of birth=1st-Jan-2006 as per Gmail ; here system and Gmail are the issuers) ClaimsIdentity ClaimsIdentity is a collection of claims of the subject (user) For example, driving license of a subject (user) can be a ClaimsIdentity that has claims like name, photo, date of birth, address etc. Passport can be a ClaimsIdentity that has claims like name, place of birth, photo, nationality, permanent address etc ClaimsIdentity also has a string property called Authenti...

Implicit usings, top level statements, file scoped namespaces in dotnet

implicit usings Implicit usings = no repeated using statement in all files With implicit usings feature in a C# project, common using statements are automatically added by the compiler in all the C# files. For example using System; statement is not required to run the dotnet console application as shown below Console . WriteLine ( "Hello World!" ) ; Additional implicit usings can be declared in a C# project with global usings statements in any one of the project’s C# files as shown below. global using Ardalis . GuardClauses ; global using MediatR ; global using Project2 . Utils ; Existing implicit usings can be removed or included in the .csproj file of the C# project as shown below < ItemGroup > < Using Remove = " System.Threading.Tasks " /> < Using Include = " System.Math " /> </ ItemGroup > The implicit usings added in a C# project is based on the project type as sh...