0% found this document useful (0 votes)
66 views52 pages

Core Middleware

Extension methods allow adding additional methods to existing classes without modifying the original class. Middleware components process HTTP requests and responses in ASP.NET Core and are arranged in a pipeline where each component can call the next. Configuring multiple middleware involves using the Use() method instead of Run() to include calling the next middleware.

Uploaded by

Reduan ahimu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views52 pages

Core Middleware

Extension methods allow adding additional methods to existing classes without modifying the original class. Middleware components process HTTP requests and responses in ASP.NET Core and are arranged in a pipeline where each component can call the next. Configuring multiple middleware involves using the Use() method instead of Run() to include calling the next middleware.

Uploaded by

Reduan ahimu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Extension Methods

C# - Extension Method
Extension methods are additional methods.

Allow you to inject additional methods


without modifying, deriving or recompiling
the original class.

Extension methods can be added to your own


custom class, .NET framework classes, or
third party classes.
C# - Extension Method
In the following example, IsGreaterThan() is an
extension method for int type, which returns
true if the value of the int variable is greater
than the supplied integer parameter.

The extension methods have a special symbol


in intellisense of the visual studio, so that you
can easily differentiate between class methods
and extension methods.
C# - Extension Method
namespace ExtensionMethods
{
public static class IntExtensions
{
public static bool IsGreaterThan(this int i, int value)
{
return i > value;
}
}
}
C# - Extension Method
• An extension method is actually a special kind of
static method defined in a static class.

• Now, define a static method as an extension method


where the first parameter of the extension method
specifies the type on which the extension method is
applicable or injected.

• So the first parameter must be int preceded with


the this modifier.
C# - Extension Method
Example: First we create a class named as Sample in 
Sample.cs file. It contains three methods that is 
M1(), M2(), and M3().

using System;
namespace ExtensionMethod {
class Sample{
   public void M1() { Console.WriteLine("Method Name: M1"); }
   public void M2() { Console.WriteLine("Method Name: M2");}
   public void M3(){ Console.WriteLine("Method Name: M3");}
  }  
}
C# - Extension Method
Now we create a static class named as NewMethodClass
in SampleEx.cs file. It contains two methods that are 
M4() and M5().
using System;
namespace NewMethodClass {
class SampleEx{
public static void M4(this Sample s)
    {
        Console.WriteLine("Method Name: M4");
    }
    public static void M5(this Sample s, string str)
    {
        Console.WriteLine(str);
    }
   }  
}
C# - Extension Method
Inside Main Method

public class MainExMethod{


     public static void Main(string[] args)
     {
         Sample s = new Sample();
         s.M1();
         s.M2();
         s.M3();
         s.M4();
         s.M5("Method Name: M5");
     }
}
}
C# - Extension Method
 Here, Binding parameters are those parameters which are
used to bind the new method with the existing class

 The Binding parameters does not take any value when


you are calling the extension method because they are used
only for binding not for any other use.

In the parameter list of the extension method binding


parameter is always present at the first place.

The binding parameter is created using 1. this keyword


followed by 2. the name of the class in which you want to
add a new method and 3. the parameter name.
For Example: this Sample s
C# - Extension Method
Advantages:
The main advantage of the extension method is to
add new methods in the existing class without
using inheritance.

You can add new methods in the existing class


without modifying the source code of the existing
class.

It can also work with sealed Class.


C# - Extension Method
Q1. Write Extension Method Called IsGreaterThan for int data type.
using ExtensionMethods;
class Program
{
static void Main(string[] args)
{
int i = 10;
bool result = i.IsGreaterThan(100);
Console.WriteLine(result);
}
}

Q2. Add Extension method to string class called ProperNameFormat


that changes the first character to upper case and the rest to lower
case.
Asynchronous programming with async, await,
Task in C#
1. synchronous programming
Example.
static void Main(string[] args)
{
LongProcess();
ShortProcess();
}
static void LongProcess()
{
Console.WriteLine("LongProcess Started");
System.Threading.Thread.Sleep(4000); Console.WriteLine("LongProcess
Completed");
}
static void ShortProcess()
{
Console.WriteLine("ShortProcess Started");
Console.WriteLine("ShortProcess Completed");
}
Asynchronous programming with async, await,
Task in C#
1. Asynchronous programming
Middleware
In ASP.NET Core, middleware is C# class (Method) that
can handle an HTTP request or response.
Middleware can :

Handlean incoming HTTP request by generating an


HTTP response.

Process an incoming HTTP request, modify it, and pass it


on to another piece of middleware.

Process an outgoing HTTP response, modify it, and pass it


on to either another piece of middleware, or the ASP.NET
Core web server.
Middleware
 Typically, there will be multiple middleware in
ASP.NET Core web application.

 It can be either framework provided middleware,


added via NuGet or your own custom middleware.

 Each middleware adds or modifies http request


and optionally passes control to the next
middleware component.
Middleware
Middleware
 Middlewares build the request pipeline. The
following figure illustrates the ASP.NET Core
request processing.
Middleware
 where a piece of middleware can call
another piece of middleware, which in turn
can call another, and so on, is referred to as a
pipeline.

 You can think of each piece of middleware as


a section of pipe—

 when you connect all the sections, a request


flows through one piece and into the next.
Middleware
Terminal Middleware ?
Configure Middleware
We can configure middleware in the Configure 
method of the Startup class using IApplicationBuilder
Note : if Asp.Net Core 6 and above Use program.cs
Example:  
public class Startup
{
public Startup() { }
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
Configure Middleware
Example : On Programs.cs File

app.Run(MyMiddleware);

async Task MyMiddleware(HttpContext context)


{
await context.Response.WriteAsync("Hello
World from My Middleware");
}
Configure Middleware
In the above example, Run() is an extension
method on IApplicationBuilder instance which
adds a terminal middleware to the application's
request pipeline.

The above configured middleware returns a


response with a string "Hello World!" for each
request.

Defines a class that provides the mechanisms to


configure an application's request pipeline.
Understand Run Method

Method Signature
public static void Run(this IApplicationBuilder ap
RequestDelegate handler)

• RequestDelegate ? It is a delegate
public delegate Task RequestDelegate (HttpContext context);

• HttpContext
It is HttpRequest http://Controller//ActionM ..
Understand Run Method

The Run method is an extension method


on IApplicationBuilder and accepts a
parameter of RequestDelegate.

The RequestDelegate is a delegate method


which handles the request.

RequestDelegate signature.
public delegate Task RequestDelegate(HttpContext context);
Understanding Run Method
public void Configure(IApplicationBuilder app)
{
app.Run(MyMiddleware);
}

 You Can write on program,cs file if Core 6 and above

app.Run(MyMiddleware);

async Task MyMiddleware(HttpContext context)


{
await context.Response.WriteAsync("Hello World! ");
}
Understanding Run Method
The above MyMiddleware function is not
asynchronous so, make it asynchronous by
using async and await to improve performance
and scalability.

async Task MyMiddleware(HttpContext context)


{
await context.Response.WriteAsync("Hello World! ");
}
Understanding Run Method
async Task MyMiddleware(HttpContext context)
{
await context.Response.WriteAsync("Hello World! ");
}

Lambda Expression

app.Run(async context => await context.Response.WriteAsync("H


World!") );
Or

app.Run(async (context) => {


await context.Response.WriteAsync("Hello World!");
});
Configure Multiple Middleware

Mostly there will be multiple middleware


components in ASP.NET Core application
which will be executed sequentially.

The Run method adds a terminal middleware


so it can’t call next middleware as it would be
the last middleware in a sequence.

The following will always execute the first


Run method and will never reach the second
Run method.
Configure Multiple Middleware

public void Configure(IApplicationBuilder app)


{
app.Run(async (context) => { await
context.Response.WriteAsync("Hello World From
First Middleware");
});
// the following will never be executed
app.Run(async (context) => { await
context.Response.WriteAsync("Hello World From 2nd
Middleware"); });
}
Configure Multiple Middleware

 To configure multiple middleware, use Use() 


extension method.

 It is similar to Run() method except that it


includes next parameter to invoke next
middleware in the sequence.

 Consider the following example.


Configure Multiple Middleware

public void Configure(IApplicationBuilder app)


{
app.Use(async (context, next) => {
await context.Response.WriteAsync
("Hello World From 1st Middleware!");
await next(); });
app.Run(async (context) => {
await context.Response.WriteAsync
("Hello World From 2nd Middleware"); });
}
Configure Multiple Middleware

ln ASP.NET Core a given Middleware


component should only have a specific
purpose i.e. single responsibility.
Where we use Middleware

We may have a Middleware component for


authenticating the user.

Another Middleware component may be used to


log the request and response.

Similarly, we may have a Middleware component


that is used to handle the errors.

We may have a Middleware component that is


used to handle the static files such as images,
Javascript or CSS files, etc.
Configure Multiple Middleware
Middleware components in the ASP.NET Core
application can have access to both HTTP Request
and Response and this is because of the above
HttpContext object.
Understanding the Use method
Signature of Use Method

• This method takes two input parameters.

• The first parameter is the HttpContext context object


through which it can access both the HTTP request and
response.

•The second parameter is the Func type i.e. it is a


generic delegate that can handle the request or call the
next middleware component in the request pipeline. 
Request Processing Pipeline:
The first two components are registered using
the Use() extension method so that they have
the chance to call the next middleware
component in the request processing pipeline.

The last one is registered using the Run() 


extension method as it is going to be our
terminating components.
i.e. it will not call the next component. 
Request Processing Pipeline:
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Middleware1: Incoming Request\n");
await next();
await context.Response.WriteAsync("Middleware1: Outgoing Response\n");
});

app.Use(async (context, next) =>


{
await context.Response.WriteAsync("Middleware2: Incoming Request\n");
await next();
await context.Response.WriteAsync("Middleware2: Outgoing Response\n");
});

app.Run(async (context) =>


{
await context.Response.WriteAsync("Middleware3: Incoming Request handled and
response generated\n");
});
Summary of Request pipeline
The ASP.NET Core request processing pipeline consists of a sequence of
middleware components that are going to be called one after the other.

Each middleware component can perform some operations before and


after invoking the next component using the next method. A middleware
component can also decide not to call the next middleware component
which is called short-circuiting the request pipeline.

The middleware component in asp.net core has access to both the


incoming request and the outgoing response.

The most important point that you need to keep in mind is the order in
which the middleware components are added in the Configure method of
the Startup class defines the order in which these middleware
components are going to be invoked on requests and the reverse order
for the response. So, the order is critical for defining the security,
performance, and functionality of the application.
Static Files Middleware
ASP.NET Core application cannot serve static
files by default.

We must include Microsoft.AspNetCore.


StaticFiles middleware in the request pipeline.
Using StaticFiles Middleware
By default, all the static files of a web application
should be located in the web root folder wwwroot.
Using StaticFiles Middleware
Now, to serve the above Default.html static file, we
must add StaticFiles middleware in
the Configure() method of Startup file as shown below.
Using StaticFiles Middleware
As you can see above, the app.UseStaticFiles() method
adds StaticFiles middleware into the request pipeline.

The UseStaticFiles is an extension method included in


the StaticFiles middleware so that we can easily
configure it.
Set Default File
As we have seen above, default.html or test.js was served
on the specific request for it. However, what if we want to
serve default html file on the root request?

To serve default.html on the root request


 http://localhost:<port>,
call UseDefaultFiles() method before UseStaticFiles() in
the Configure method as shown below.
Set Default File
This will automatically serve html file named
default.html, default.htm, index.html or index.htm
on the http request http://localhost:<port>.

Order of middleware is very


important. app.UseDefaultFiles() should be added
before app.UseStaticFiles() in the request pipeline.
Set Default File
As
 we learned in the Set Default File section, app.UseDefaultFiles() middlewar
serves the following files on the root request.

1.Default.html
2.Default.htm
3.Index.html
4.Index.htm

Note: You need to add the UseDefaultFiles() 


middleware before the UseStaticFiles() middleware in
order to serve the default file. The point that you need
to remember is the UseDefaultFiles() middleware is just
a URL rewriter and it never serves the static files.
The job of this middleware is to simply rewrite the
incoming URL to the default file which will then be served
by the Static Files Middleware.
Set Default File
Suppose,
 you want to set home.html as a default page which should be displayed
on the root access. To do that, specify DefaultFilesOptions in
the UseDefaultFiles method as shown below.
Developer Exception Middleware
By default, ASP.NET Core returns a simple
status code for any exception that occurs in an
application.
Developer Exception Middleware
To handle exceptions and display user friendly
messages, we need to
install Microsoft.AspNetCore.Diagnostics
NuGet package.

The Microsoft.AspNetCore.Diagnostics packag
e includes following extension methods to
handle exceptions in different scenario:
1. UseDeveloperExceptionPage
2. UseExceptionHandler
UseDeveloperExceptionPage

The UseDeveloperExceptionPage extension
method adds middleware into the request
pipeline.

 which displays developer friendly exception


detail page.

This helps developers in tracing errors that


occur during development phase.
UseDeveloperExceptionPage

The developer exception page includes 4 tabs:


Stack, Query, Cookies, and Headers.

Stack tab displays information of stack trace,


which indicates where exactly an error
occurred.
How to Customize the UseDeveloperExceptionPage

The number of lines of code to include before


and after the line of code that caused the
exception.
UseDeveloperException Example

You might also like