HTTP (HyperText Transport Protocol)
HTTP (Hypertext Transport Protocol) i.e. HTTP Verbs or Methods (post, get, put, delete, patch), HTTP
Status Codes, HTTP Requests, and Responses.
1. How browser and Server Communicate with Each Other?
2. What is HTTP (HyperText Transport Protocol)?
3. Understanding HTTP Request and Response.
4. HTTP Verbs or HTTP Methods
5. HTTP Status Codes
How browser and Server Communicate with Each Other?
HTTP stands for HyperText Transport Protocol. HTTP is used for communication between the client and server
Browser is not the only client. For example, if you are using a mobile application, then your mobile is a client. If
you are calling APIs using tools like Postman and Fiddler, then Postman and Fiddlers are also the clients.
What is HTTP?
1. Hypertext Transfer Protocol (often abbreviated to HTTP) is a communications protocol. It is used to send
and receive web pages and files on the internet. It was developed by Tim Berners-Lee and is now
coordinated by the W3C. HTTP version 1.1 is the most commonly used version today. It is defined in
RFC 2616.
2. The Hypertext Transfer Protocol (HTTP) is an application layer protocol for distributed, collaborative,
hypermedia information systems. HTTP is the foundation of data communication for the World Wide
Web, where hypertext documents include hyperlinks to other resources that the user can easily access,
for example by a mouse click or by tapping the screen in a web browser.
HTTP Response Components:
Whatever we get from the webserver to the clients called HTTP Response. The HTTP response contains the
following components.
1. HTTP Status Code: It must have a Status Code.
2. Response Headers: It can have one or more response headers.
3. Data: Response can have data i.e. return to the client.
Along with the above three components, other components are also there. But the above three components are
the important components in an HTTP Response.
[Link] Core Web API Files and Folders
Properties:
The Properties Folder in [Link] Core Web Application by default contains one JSON file called as
[Link] file as shown in the below image.
[Link] file is only used within the local development machine
The [Link] file contains some settings that are going to be used by .NET Core Framework when
we run the application either from Visual Studio or by using .NET Core CLI.
[Link] file:
This is the same as [Link] or [Link] of our traditional .NET Application.
The [Link] file is the application configuration file in [Link] Core Web Application used to store
the configuration settings such as database connections strings
[Link] class file:
The Main method is the entry point of our Application.
[Link] class file:
The Startup class is like the [Link] file of our traditional .NET application. As the name suggests, it is
executed when the application starts. You will find the following code in your Startup class.
namespace MyFirstWebAPIProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the
container.
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link](c =>
{
[Link]("v1", new OpenApiInfo { Title = "MyFirstWebAPIProject", Version =
"v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP
request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if ([Link]())
{
[Link]();
[Link]();
[Link](c => [Link]("/swagger/v1/[Link]",
"MyFirstWebAPIProject v1"));
}
[Link]();
[Link]();
[Link]();
[Link](endpoints =>
{
[Link]();
});
}
}
}
ConfigureServices() method:
The ConfigureServices method of the Startup class is the place where we can register our dependent classes
with the built-in IoC container. Once we register the dependent classes, they can be used anywhere within the
application. The ConfigureServices method includes the IServiceCollection parameter to register services to the
IoC container.
If you notice, currently it adds two services i.e. AddControllers and AddSwaggerGen to the build-in IoC
Container
(inversion of control sold principle)
as shown in the below image.
Configure () method:
The Configure method of the Startup class is the place where we configure the application request pipeline
using the IApplicationBuilder instance that is provided by the built-in IoC container. [Link] Core introduced
the middleware components to define a request pipeline, which will be executed on every request. If you look at
the Configure method, it registered UseDeveloperExceptionPage, UseSwagger, UseSwaggerUI,
UseHttpsRedirection, UseRouting, UseAuthorization, and UseEndpoints middleware components to the
request processing pipeline as shown in the below image. We will discuss each middleware component in
detail in our upcoming articles.
ConfigureServices vs Configure
ConfigureServices
Even though we will almost always use this method, it is an optional method.
If ConfigureServices exists on Startup class, it will be called by the Web host. Of course, for this to happen
Web host has to instantiate Startup first. Therefore, Startup constructor will execute
before ConfigureServices. We will usually have our configuration and logging setup inside of the
constructor.
You will notice that by default ConfigureServices has one parameter, of
type IServiceCollection. IServiceCollection is a container. Adding services to this container will make them
available for dependency injection. That means we can inject those services anywhere in our application.
public void ConfigureServices(IServiceCollection services)
2{
3 [Link]<IEmailSender, EmailSender>();
4}
Configure
Inside of Configure method we set up middleware that handles every HTTP request that comes to our
application:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if ([Link]())
{
[Link]();
}
[Link]();
[Link]();
}
We should keep our Configure method clean and in the case of having large chunks of code that are
processing request we should move those to our middleware.
Ordering matters in Configure method, so first piece of code inside of the method will process the request
first. It can either make a response or pass the request to the next piece of middleware.
Summary
ConfigureServices is used to add services to our application
We can use services via integrated DI once we add them inside of ConfigureServices
Services added to DI can be utilised within our application
Configure method is used to set up middleware
We manage HTTP request pipeline inside of Configure method
Inside of Configure method, we write code that will process every request and eventually make a
response
[Link] Core Web API – Middleware
HTTP Request Pipeline:
Before hitting the controller action method, the request has to pass through a pipeline. Once the pipeline is
completed, then only it navigates the request to the corresponding controller action method as shown in the
below image.
Middleware is a piece of code that is used in the HTTP Request Pipeline. An [Link] Core Web API
Application can have n numbers of middleware. So, depending upon the requirement, we can configure n
numbers of middleware in the application request processing pipeline.
The order of middleware matters a lot in the execution. That means in the order they are configured into the
request processing pipeline; in the same order, they are going to be executed when a request comes. Each
middleware in the [Link] Core Web API Application performs the following tasks.
1. Chooses whether to pass the HTTP Request to the next component in the pipeline. This can be
achieved by calling the next() method within the middleware.
2. Can perform work before and after the next component in the pipeline.
[Link] Core provides some built-in middleware that is ready to be used, even if you want then you can also
create your own custom middleware. The most important point that you need to keep in mind is, in [Link]
Core a given Middleware component should only have a specific purpose i.e. single responsibility.
Middleware Examples:
1. Routing: If you want to implement Routing in your application, then you need to use Routing
Middleware in the HTTP Request Processing pipeline.
2. Authentication: If you want to authenticate the user then you need to use Authentication Middleware.
3. Authorize: The Authorize Middleware is used to Authorize the users while accessing a specific
resource.
4. Log: If you want to log request and response while processing, then you need Middleware.
5. Exception Middleware: You can also use Middleware to handle the exception globally.
Note: The Middleware in [Link] Core Web API Application is used to set up the HTTP Request processing
pipeline. If you have prior experience of the previous .NET Framework then you may know, HTTP Handlers and
HTTP Modules which are basically used to set up the request processing pipeline. It is this pipeline that will
determine how the HTTP request and response are going to be processed.
How to Configure Middleware Components in [Link] Core application?
In the [Link] Core Web API application, the Middleware components are configured within the Configure
method of the Startup class. The Startup class is the class that is going to run when the application starts. The
following is the Configure method of the Startup class that we have created in our previous article. Even though
if you created an [Link] Core Application with an Empty Project template, then also you will find the
following code within the Configure method of the Startup class.
As you can see in the above image, within the Configure method we have configured three Middleware
components to the HTTP Request Processing Pipeline. They are as follows.
1. UseDeveloperExceptionPage() Middleware: The UseDeveloperExceptionPage() middleware will
come into picture only when the hosting environment is set to “development”. The
UseDeveloperExceptionPage middleware is going to execute when there is an unhandled exception that
occurred in the application and since it is in development mode, it is going to show you the detailed
information of the exception.
2. UseRouting() Middleware: The UseRouting middleware is used to add Endpoint Routing Middleware
to the request processing pipeline i.e. it will map the URL (or incoming HTTP Request) to a particular
resource.
3. UseEndpoints() Middleware: In this middleware, the routing decisions are going to be taken using the
Map extension method.
So, if you want to configure any middleware components in any type of [Link] Core applications, then you
need to configure it within the Configure method by calling the Use* methods on the IApplicationBuilder object.
Note: The [Link] Core Middleware components are executed in the same order as they are added to the
pipeline. So, it is our key responsibility to take care when adding middleware components.
1. Run() Method: The Run() Extension Method is used to complete the Middleware Execution.
2. Use() Method: The Use() Extension Method is used to insert a new Middleware component to the
Request Processing Pipeline.
3. Next() Method: The Next() Extension Method is used to call the next middleware component in the
request processing pipeline.
4. Map() Method: The Map() Extension Method is used to map the Middleware to a specific URL.
Run, Use, and Next Method in [Link] Core
Run Method in [Link] Core
The Run method in [Link] Core Application is used to complete the Middleware Execution. That means the
Run extension method allows us to add the terminating middleware component. Terminating middleware
means the middleware which will not call the next middleware components in the request processing pipeline.
The Run Extension method is used for adding terminal middleware that means Adds a terminal middleware
delegate to the application’s request pipeline. This method takes two Parameters:
1. app: The [Link] instance.
2. handler: A delegate that handles the request.
Modifying the Configure Method of Startup class:
Let us create a middleware using the Run method. As we already discussed if want to add middleware, then we
need to add the same inside the Configure method of the Startup class. Let us add the following Middleware to
the Request processing Pipeline.
Use () and Next () Extension Methods in [Link] Core
The Use Extension Method in [Link] Core is used to add a new Middleware component to the Request
Processing Pipeline whereas the Next Extension Method in [Link] Core is used to call the next middleware
component configured in the request processing pipeline.
Z
Custom Middleware in [Link] Core
In order to make a class a Middleware component, the class needs to be inherited from the IMiddleware
interface. Further IMiddleware interface belongs to [Link] namespace. And we need to
implement the InvokeAsync method. And you need to write your logic within the InvokeAsync method. So,
modify the MyCustomMiddleware1 class as shown below.
using [Link];
using [Link];
namespace MiddlewareInASPNETCore
{
public class MyCustomMiddleware1 : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await [Link]("Custom Middleware Incoming Request \n");
await next(context);
await [Link]("Custom Middleware Outgoing Response \n");
}
}
}
Now we need to use it in our HTTP Request Processing pipeline. Now it is a two-step process to use this
custom middleware component.
Step1: Inject the service to the built-in dependency injection container
Remember if you want to use any custom service, before using it, you must inject the service into the built-in
IoC Container. You can inject the service using the ConfigureService method of the Startup class
as [Link]<MyCustomMiddleware1>();. We will discuss AddTransient and its working in
detail while we discuss dependency injection
public void ConfigureServices(IServiceCollection services)
{
[Link]();
[Link]<MyCustomMiddleware1>();
}
Step2: Registering the Custom Middleware in the HTTP Request Processing Pipeline
Once you configure the service to the built-in IoC Container, then you can use the Middleware. As we already
discussed we can configure the Middleware to the Request Processing Pipeline using the Configure method of
the Startup class. To configure the custom Middleware we need to use the UseMiddleware Extension method
as [Link]<MyCustomMiddleware1>();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
[Link](async (context, next) =>
{
await [Link]("Use Middleware Incoming Request \n");
await next();
await [Link]("Use Middleware Outgoing Response \n");
});
[Link]<MyCustomMiddleware1>();
[Link](async context => {
await [Link]("Run Middleware Component\n");
});
}