Understanding ASP.NET Middleware

Understanding ASP.NET Middleware

In ASP.NET Core, middleware is the term used for components that form the Request Pipeline.

The pipeline request is similar to a chain; it can contain multiple middleware. These components will handle the request in sequence; each component will inspect the request and decide whether it should be passed to the next middleware or just generate a response interrupting the chain.

Once the request has been handled, a response will be generated and send back to the client passing along the chain.

Execution Order

Middleware’s will execute in the same order they are registered when handling requests and in the reverse order when handling responses.

Check the example below:

How to create a Middleware

Middleware components don’t implement interfaces or derive from classes, It simply has a constructor that takes RequestDelegate as parameter and implements the Invoke Method.

The RequestDelegate represents the next Middleware component of the chain and the Invoke method is called when the component receives a request.

For example:

Creating Content-Generating Middleware

The most important type of middleware generates content for clients, and it is this category to which MVC belongs.

This kind of middleware is used when you want to generate some content and send it back to the client without the need of dealing with all the MVC complexity.

Implementation:

 

Creating Short-Circuiting Middleware

Short-Circuiting Middleware Components are used when you want to inspect the request and decide if the request should be passed to the next component.

For example, the below process is checking if the request contains the User-Id header, if not the middleware will break the chain and return a 401-Unauthorized response to the client.

 

Creating Request-Editing Middleware

The next type of middleware component examined doesn’t generate a response. Instead, it changes requests before they reach other components later in the chain. This kind of middleware is mainly used for platform integration to enrich the ASP.NET Core representation of an HTTP request with platform-specific features.

The example below is to demonstrate the check that if the request contains a blank User-Id in the header; if yes it will be removed.

 

 

Interacting with another Middleware

Middleware components can interact with each other, let’s consider that RequestEditMiddleware is executed before the ShortCircuitMiddleware.

In that case if a request contains blank User-Id Header the RequestEditMiddleware will remove that header from the request and call the next component, which is the ShortCircuitMiddleware, the ShortCircuitMiddleware won’t find the header User-Id and will break the chain returning a 401 response to the client.

Registering a Middleware

Now that we already know how to create our own custom components, how do we use it?

It’s simple, in the Startup class there is a method called Configured which is responsible to setup how the application will handle requests.

This method has a parameter of type IApplicationBuilder, that is the object we use to register our components.

See example below:

However, there is a more efficient way to register the components, for that we need to create some extension methods.

See below:

After creating the extension methods all we have to do is register the components using it.

 

ASP.NET Core and Docker for Beginners

Introduction:

Docker is an open, lightweight platform for developing, shipping and running applications using container technology. Docker provides container solutions for developers, architects, DevOps, and IT People. It can run on Linux, Windows, Mac OS and most the cloud providers like AWS, Azure, Google etc..

What is Docker?

Docker is all about running a single program inside separated environments. It is an open source platform with can be used to package, distribute and run applications in different environments.

Let start understanding by an example,


Applications 1 & 3 will stop working because they need a different framework to run. What can be done now? The above diagram shows, we have three applications running; however, all of the application use the same framework. What will happen if App 1 required different Framework version like 1.0, app 2 needs v2.0, app 3 needs v.3.0. As a result only App 2 will work because our framework installed is v2.0.

One way is to use three different systems for all three applications, but it will be very expensive and maintening them will also be very difficult.

This is how “DOCKER” comes into play. Docker will make sure each application has its own facilities rather than common facilities.

Docker will do something like this.


Build the ASP.Net Core and Docker Packages

Docker will create a package that can run in different environments.

To build an app in Docker, first we need an app to Dockerize.

Docker allows you to build an application in pretty much the same way you would create an application to run on your local machine.

When we create application make sure enable the Docker support and also make sure you have it installed by going to:

https://www.docker.com/products/docker-desktop

Note: Make sure Docker is installed .Otherwise you’ll get the below error:

Installing this (mac or pc) will run docker and allow you to create and host docker containers. Microsoft Visual Studio will use Docker Desktop to host your app inside of during development to allow you to develop or test in.

The trick is to get a new item in your launchSettings.json:

This, in conjunction with a docker file in your project (just called “Dockerfile” without an extension) that builds a container, hosts it, and allows you to debug it remotely.

Writing a Dockerfile:

What is Dockerfile?

In short, Dockerfile contains a series of instructions which define how to construct an image:

Below are the common commands:

FROM

This command specifies the base image, eg: Microsoft/aspnetcore:2.0

WORKDIR

Changes the working directory for subsequent instructions in the Dockerfile

COPY

Copies files from source to destination

RUN

Executes a command directly in the container

EXPOSE

Sets a specific port internally to the container

VOLUME

Usually, it is used to map a physical directory on our machine to the logical directory in the container instead.

ENTRYPOINT

Specifies which application will run in the container created from the image.

To use some of the commands, First create Dockerfile in your application:

Then write Dockerfile for ASP.NET Core app, you must first know if you want to use the Development Environment or the Production Environment.

In development environment you need an image that contains a compiler and allows compiling directly in the container, and for that, use Microsoft/aspnetcore-build directly from the DockerHub (Docker Repository).

In Production environment you do not need a compiler because it will have to build the application externally from the image, integrate all built files in the image, and just use a lightweight image containing the .NET Core Runtime Microsoft/aspnetcore to execute your application.

The Dockerfile is pretty simple (if you’re familiar with Docker) though it’s very automated, so you don’t have to know how it works:

It creates a container from a slim image with ASP.NET Core 2.2 , builds the project and publishes to get a copy of the project in a container. To test/debug with docker, just pick the ‘Docker’ option in the debugging dropdown:

After that, in cmd type:

docker build. –t rootandadmin/DockerApp –f Dockerfile

Now, you have your image and check the type:

docker images

You have your image rootandadmin/DockerApp but as this image is dead so you have to make it alive. For this you will need to create a container. There is a big difference between Image and Container; a container is a process that contains an image and executes it.

Then to create containers from our image type this.

docker create command –p 555:80 –name rootandadmin/DockerApp01 rootandadmin/DockerApp

docker start rootandadmin/ DockerApp01

You can try to access your DockeApp in the browser using the following address.

localhost://555/ DockerApp/Home

RESTful API Designing Guidelines

Your introduction for everything REST and how to understand it.

What is REST?

Representational state transfer (REST) is a software architectural style that defines a set of constraints to
be used for creating Web services. Web services that conform to the REST architectural style, called
RESTful Web services, provide interoperability between computer systems on the Internet.

Terminologies

The following are the most important terms related to REST APIs:

Resource
Resource is an object or representation of something, which has some associated data with it and
can be set methods to operate on it.
E.G Company

Collections
Collections are a set of resources.
E.G Companies is the collection of the Company Resource.

URL
URL (Uniform Resource Locator) is a path through which a resource can be located and actions can
be performed on it.

API Endpoint
In simple terms, an API endpoint is the point of entry in a communication channel where two systems are
interacting. It refers to a touch point of communication between an API and the server.
The location where the API sends a request and where the response emanates is what is known as an
endpoint.

API vs Endpoint
An API refers to a set of protocols and tools that allow interaction between two different applications. It is a technique that enables third-party vendors to write programs that can easily interface with each other. On the other hand, an endpoint is the place of interaction between applications. API refers to the whole set of protocols that allows communication between two systems while an endpoint is a URL that enables the API to gain access to resources on a server.

Web Api Endpoint Naming Convention

Methods Naming Convention
In OOP methods are named with verbs to make it easier to identify what operation that method will
perform, for example the method GetEmployees(int departmentID) will return all the employees that
belongs to a department.

Should we use the same naming convention when designing web Api’s endpoints?
The answer is NO.
Web Api endpoints must be names with NOUNS instead of verbs and it should contain the plural form of
the Resource the api will perform operations on.

Example: https://www.estradaci.com/apis/v1/Employees

If the URL can’t contain verbs, how do we know which action will be performed?
HTTP Verbs will be responsible for telling which action the WEB API should perform.
Let’s look at the most used HTTP Verbs used while creating WEB APIs.

HTTP VERBS.

GET
Use GET requests to retrieve resource representation/information only – and not to modify it in any
way. As GET requests do not change the state of the resource, these are said to be safe methods.
Additionally, GET APIs should be idempotent, which means that making multiple identical requests must
produce the same result every time until another API (POST or PUT) has changed the state of the
resource on the server.

Examples:
 GET https://www.estradaci.com/apis/v1/Employees
 GET https://www.estradaci.com/apis/v1/Employees/1
 GET https://www.estradaci.com/apis/v1/Employees?name=Jeff
All the endpoints above will fetch employees but using different inputs to query the employees.

HTTP POST
Use POST APIs to create new subordinate resources, e.g. a file is subordinate to a directory containing it
or a row is subordinate to a database table. Talking strictly in terms of REST, POST methods are used to
create a new resource into the collection of resources.
Examples:
 POST https://www.estradaci.com/apis/v1/Employees
 POST https://www.estradaci.com/apis/v1/Employees/Address

Both endpoints above will insert data in the database, the first one will create a new employee and the
second one will create an address for an employee.

HTTP PUT
Use PUT APIs primarily to update existing resource (if the resource does not exist then API may decide to
create a new resource or not). If a new resource has been created by the PUT API, the origin server
MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing
resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to
indicate successful completion of the request.
Examples:
 PUT https://www.estradaci.com/apis/v1/Employees
 PUT https://www.estradaci.com/apis/v1/Employees/Address

Both endpoints above will update data in the database, the first one will update an employee and the
second one will update the employee`s address.

HTTP DELETE
As the name applies, DELETE APIs are used to delete resources (identified by the Request-URI).
Examples:
 DELETE https://www.estradaci.com/apis/v1/Employees
 DELETE https://www.estradaci.com/apis/v1/Employees/Address

Both endpoints above will delete data from the database, the first one will delete an employee and the
second one will delete the employee`s address.
As we can see the same URL can perform different actions when requested with different HTTP Verbs.

For example the https://www.estradaci.com/apis/v1/Employees can Get, Create, Update and Delete
employees based on the HTTP Verb used.

HTTP response status codes

Sometimes when the client sends a request to the server it expects a response indicating the result of the
operation. it’s a good practice to return coherent status codes to make it easy to the client understand what
happened when the request is processed.
HTTP defines standard status codes that can be used to convey the results of a client’s request. The
status codes are divided into the five categories presented below.

CATEGORY DESCRIPTION

1xx: Informational Communicates transfer protocol-level information.

2xx: Success Indicates that the client’s request was accepted successfully.

3xx: Redirection Indicates that the client must take some additional action in order to complete their request.

4xx: Client Error This category of error status codes points the finger at clients.

5xx: Server Error The server takes responsibility for these error status codes.

Check below the description of the most used Status Codes used when creating a web api.

For a complete list of the HTTP Status Codes check https://docs.microsoft.com/en-
us/dotnet/api/system.net.httpstatuscode?view=netframework-4.8

200 (OK)
It indicates that the REST API successfully carried out whatever action the client requested, and that no
more specific code in the 2xx series is appropriate.

201 (Created)
A REST API responds with the 201 status code whenever a resource is created inside a collection. There
may also be times when a new resource is created as a result of some controller action, in which case
201 would also be an appropriate response.

204 (No Content)
The 204 status code is usually sent out in response to a PUT, POST, or DELETE request when the REST
API declines to send back any status message or representation in the response message’s body.
An API may also send 204 in conjunction with a GET request to indicate that the requested resource
exists, but has no state representation to include in the body.

304 (Not Modified)
This status code is similar to 204 (“No Content”) in that the response body must be empty. The key
distinction is that 204 is used when there is nothing to send in the body, whereas 304 is used when the
resource has not been modified since the version specified by the request headers If-Modified-Since or
If-None-Match.

400 (Bad Request)
400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can
be like malformed request syntax, invalid request message parameters, or deceptive request routing
etc.
The client SHOULD NOT repeat the request without modifications.

401 (Unauthorized)
A 401 error response indicates that the client tried to operate on a protected resource without providing
the proper authorization. It may have provided the wrong credentials or none at all.

404 (Not Found)
The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may
be available in the future. Subsequent requests by the client are permissible.

500 (Internal Server Error)
500 is the generic REST API error response. Most web frameworks automatically respond with this
response status code whenever they execute some request handler code that raises an exception.

Content Negotiation

When sending a request to an API we need to tell the server what is the type of the data we are sending
and the server is responsible to tell the client the same.

At server side, an incoming request may have an entity attached to it. To determine it’s type, server
uses the HTTP request header Content-Type.

Some common examples of content types are :“text/plain”, “application/xml”, “text/html”, “application/json”, “image/gif”, and “image/jpeg”.

Content-Type: application/json
Similarly, to determine what type of representation is desired at client side, HTTP header ACCEPT is
used. It will have one of the values as mentioned for Content-Type above.
Accept: application/json

The most used content-type used by APIS to represent the object the is being sent to the server or
returned to the client is JSON, make sure to use the camelCase naming convention when using JSON.

API Versioning
One of the most important things in WEB API development is the versioning.
WEB APIs must be well versioned in order to prevent the clients that are consuming it to break.

When a Break Change is made to an existing WEB API, instead of modifying the existing one we must
create a new version of it.

For example:
Several changes are required to be made on the WEB API
https://www.estradaci.com/apis/v1/Employees and these changes may lead the consumers to break
their integrations.
Instead of simply applying the changes to this API we need to create a new version of the api, E.G
https://www.estradaci.com/apis/v2/Employees.
This will prevent the clients that are consuming the V1 to break and will give them the time and
flexibility to migrate their calls to the V2.

REST vs. gRPC – The Battle Over Service Orientation

Rest Vs. gRPC

Services are a common talk between developers and companies that are in the process of implementing software; they are an important piece in any project architecture as they separate layers of functionality and offer the flexibility of implementing different levels of security in between layers. Their implementation can vary from serving data from the database servers, sending messages to other servers, and much more.

In .NET technologies there used to exist an entire framework dedicated to services and Windows Communication Foundation, this collection of tools would help set up services in a variety of protocols. On the downside, they were closely coupled with .NET, making the configuration of services more complex than some of the most popular options of its time.

Then came REST, a new portable way of communicating clients and servers via TCP, making them accessible over the internet. Most of the big web sites implement REST APIs to provide information to the outside world (such as Google, Twitter, LinkedIn, etc.). This model is based on Request-Response model that will return a text-based response (JSON, XML, HTML), currently the standard is JSON (JavaScript Object Notation). This is a flexible way to work with objects without depending on the platform.

The Problem…

The problem with JSON comes when you have a high demand application (server or client) that will make a large amount of request/responses. If you have to serialize/deserialize the objects to your native types, it will add an extra conversion overhead. If you are not having a outword facing application, you mostly have the same technologies applied in both sides of the communication, meaning that the service will have to take the response object from C#, serialize it to JSON and send it back to the client. Then the client will take the response JSON and deserialize back to your C# object. This is by no means hard to achieve, but the processing time may be impacted by the workload of your application.

There is a solution!

To solve this, we have RPC (Remote Procedure Call). This communication is based on Protocol Buffers, a mechanism to serialize data (the data is serialized in raw format). It offers all the main functionalities that REST does, with the added option for bidirectional streams that allow the client and server to communicate asynchronously that result in faster times. The configuration steps to get a gRPC service may seem a little more complex and limited than REST (Protocol Buffers currently supports generated code in C++, Go, Java, Phyton, Ruby and C#), but the benefit of faster performance may compensate.

In conclusion.

Current implementation of services using gRPC came with the adoption of Cloud computing and microservices with high performance demand. So, if you are planning create or enhance a service take a look at the past first, then present technologies and the future of your implementation in order to make the correct call. In conclusion, REST is still the most simple and portable solution if you don’t have an issue with communication performance.

If you want to know more about gRPC go to https://grpc.io/docs/guides/

Choosing between .NET Core and .NET Framework for server apps

There are two supported implementations for building server-side applications with .NET: .NET Framework and .NET Core. Both share many of the same components and you can share code across the two. However, there are fundamental differences between the two and your choice depends on what you want to accomplish.

Use .NET Core for your server application when:
• You have cross-platform needs.
• You are targeting microservices.
• You are using Docker containers.
• You need high-performance and scalable systems.
• You need side-by-side .NET versions per application.

Use .NET Framework for your server application when:
• Your app currently uses .NET Framework (recommendation is to extend instead of migrating).
• Your app uses third-party .NET libraries or NuGet packages not available for .NET Core.
• Your app uses .NET technologies that aren’t available for .NET Core.
• Your app uses a platform that doesn’t support .NET Core.

Top reasons to choose .NET Core

Cross-platform Needs
If your application needs to run on multiple platforms like Windows, Linux, and macOS, use .NET Core; it supports the previously mentioned operating systems as your development workstation. Visual Studio provides an Integrated Development Environment (IDE) for Windows and macOS. You can also use Visual Studio Code, which runs on macOS, Linux, and Windows. Visual Studio Code supports .NET Core, including IntelliSense and debugging. Most third-party editors, such as Sublime, Emacs, and VI, work with .NET Core. These third-party editors get editor IntelliSense using Omnisharp. You can also avoid any code editor and directly use the .NET Core CLI tools, available for all supported platforms.

Need for High-performance and Scalable systems
When your system needs the best possible performance and scalability, .NET Core and ASP.NET Core are your best options. High-performance server runtime for Windows Server and Linux makes .NET a top performing web framework on TechEmpower benchmarks.Performance and scalability are especially relevant for microservices architectures, where hundreds of microservices may be running. With ASP.NET Core, systems run with a much lower number of servers/Virtual Machines (VM). The reduced servers/VMs save costs in infrastructure and hosting.

Microservices Architecture
Micro services architecture allows a mix of technologies across a service boundary. This technology mix enables a gradual embrace of .NET Core for new microservices that work with other microservices or services. For example, you can mix microservices or services developed with .NET Framework, Java, Ruby, or other monolithic technologies Need for side by side of .NET versions per application level To install applications with dependencies on different versions of .NET, we recommend .NET Core. .NET Core offers side-by-side installation of different versions of the .NET Core runtime on the same machine. This side-by-side installation allows multiple services on the same server, each of them on its own version of .NET Core. It also lowers risks and saves money in application upgrades and IT operations.

Need to use .NET Technologies Not Available for .NET Core
Some .NET Framework technologies aren’t available in .NET Core. Some of them might be available in later .NET Core releases. Others don’t apply to the new application patterns targeted by .NET Core and may never be available.

The following list shows the most common technologies not found in .NET Core:

ASP.NET Web Forms applications:
• ASP.NET Web Forms are only available in the .NET Framework.
• ASP.NET Core cannot be used for ASP.NET Web Forms.
• There are no plans to bring ASP.NET Web Forms to .NET Core.

ASP.NET Web Pages applications:
• ASP.NET Web Pages aren’t included in ASP.NET Core.

WCF services implementation:
Even when there’s a WCF-Client library to consume WCF services from .NET Core, WCF server implementation is currently only available in the .NET Framework. This scenario is not part of the current plan for .NET Core but it’s being considered for the future.

Workflow-related services:
Windows Workflow Foundation (WF), Workflow Services (WCF + WF in a single service) and WCF Data Services (formerly known as “ADO.NET Data Services”) are only available in the .NET Framework. There are no plans to bring WF/WCF+WF/WCF Data Services to .NET Core.

Language support:
Visual Basic and C# are currently supported in .NET Core, but not for all project types. For a list of supported project templates, see Template options for dot net new.

In addition to the official roadmap, there are other frameworks to be ported to .NET Core. For a full list, see the CoreFX issues marked as port-to-core. This list doesn’t represent a commitment from Microsoft to bring those components to .NET Core. They’re simply capturing the desire from the community to do so. If you care about any of the components marked as port-to-core, participate in the discussions on GitHub. And if you think something is missing, file a new issue in the CoreFX repository (Some References are taken from MSDN).

ASP.NET Core with EF Core and RESTful API
ASP.NET Core is an open source, cross-platform framework for building modern internet connected applications, and ASP.NET Core MVC is a middleware which provides a framework for building the APIs and web application using MVC pattern. (Click here to learn more about ASP.NET Core)

Create an ASP.NET CORE application
Open Visual Studio, File -> New ->Project, select ASP.NET Core web application template and click OK

Choose an API template as shown below

By clicking on OK, it will create a new ASP.NET Core project with some pre-defined configuration files and controller.

The program.cs class which contains the main method with a method called Createwebhostbuilder(), is responsible for running and configuring the application. The host for the application is set up with the startup type as startup class.

The startup.cs class contains two important methods:

ConfigureServices() – it is used to add service to build dependency injection containers and configure those services,
Configure() – it is used to configure how the ASP.NET Core application will response to an individual HTTP request.

Configure the Entity Framework Core

Create a folder called Entities to organize the entity model classes. Let’s create an entity model class.

Creating a Context File

Let’s create a context file, add a new class file, and name it as LibraryContext.cs.

Define the database connection in appsettings.json file and let’s register our context in Startup.cs.

Generate Database from Code-first Approach
Run the following command in the Package Manager console.
-Add-Migration MyCoreAPIDemo.Entities.LibraryContext

This will create a class for migration. Run the following command to update the database.
-Update-database

This will update the database based on our models.

Adding Data
Let’s add some data to the Author table. For this, we need to override a method OnModelCreating in the LibraryContext class.

LibraryContext.cs

Let’s run the migration and update command once again.

Creating a Repository
Let’s add a repository folder to implement the repository pattern to access the context method.

Create two more folders – Contract and Implementation – under the repository folder.

Create an interface ILibraryRepository.cs under Contract folder.

ILibraryRepository.cs

Let’s create a class under implementation folder to implement the function.

LibraryRepository.cs

The above method GetAllAuthor() will return the complete list of records from Author table.

Let’s configure the repository using dependency injection. Open Startup.cs file, add the below code in Configuration Services method.

Create API Controller

Right-click on controller and go to Add->Controller. Choose an empty API template and name the controller. I named the controller as LibrariesController.

We have created a WEB API with an endpoint api/Libraries/GetAllAuthor to get an author list from the database.

Let’s test the API using Postman tool.

We got an author list as a response.

 

CREATE using Entity Framework with ASP.Net Core

Open the LibraryRepository.cs file from the application and write the below code.

_libraryContext is our database context, the Add method is used to add the records in the entity, and the SaveChanges method is used to save the changes in the database.

Open LibrariesController.cs file from the application and write this code.

The AddAuthor action will fetch the data from the body of request. Once the modelstate is validated, the data will be added to the database by calling the PostAuthor method in repository.

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/AddAuthor

From the above image, you can notice that the data is successfully added and returned

Changes in the database

READ
We already discussed about GetAllAuthor() read method in my last article. Now, I’m giving a demo of the method which is used to read the data from the database based on Id.

Open the LibraryReporsitory.cs file from the application and write the following code into it.

Open the LibrariesController.cs file from the application to add the below code.

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/DeleteAuthor?authorId=04dcc177-9a0a-4444-4aff-08d694b67230

From the above image, you can notice the author data is returned based on the author id.

UPDATE
Open LibraryRepository.cs file and update it with the given code.

_libraryContext is our database context, the Update method is used to update the records in the entity, and the SaveChanges method is used to save the changes in the database.

Open LibrariesController.cs file from the application and write the below code.

The UpdateAuthor action will fetch the data from the body of request. Once the modelstate is validated, the data will be updated in database by calling the UpdateAuthor method in the repository.

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/UpdateAuthor

From the above image, you can notice that the author data is updated based on the request.

Changes in the Database

DELETE

Open the LibraryRepository.cs file from the application and add the following code.

The Remove method is used to remove the records in the entity, the SaveChanges method is used to save the changes in the database based on update done in data entity.

Open LibrariesController.cs file from the application and write this code.

The DeleteAuthor method will delete the record by calling the DeleterAuthor method in the repository based on the author id passed through the request.

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/DeleteAuthor?authorId=04dcc177-9a0a-4444-4aff-08d694b67230

From the above image, you can notice that we got a response as 1 which means the data is deleted successfully based on the request.

Conclusion

We saw how to create a ASP.NET Core with EF Core and RESTful API .
We will see more about ASP.NET Core in future articles.