Asp.Net Core-Middleware
In this chapter, we will learn how to set up middleware. Middleware technology in ASP.NET Core controls how our applications respond to HTTP requests. It can also control application exception errors, which is a key in how users are authenticated and authorized to perform specific actions.
Middleware is a software component assembled into an application's pipeline to handle requests and responses.
Each component can choose whether to pass the request to the next component in the pipeline, and can perform certain actions before and after tasks in the pipeline.
The Request delegate is used to build the request pipeline. The Request delegate is used to handle each HTTP request.
Every piece of middleware in ASP.NET Core is an object, and each piece has a very specific, focused and limited role.
Ultimately, we need a lot of middleware to provide appropriate behavior for the application.
Now let’s assume we want to log every request to our application.
In this case, the first piece of middleware we install into the application is a logging component.
This logger can see all incoming requests, and then the middleware just logs some information, and then passes the request to the next block of middleware.
Middleware appears in this processing pipeline as a series of components.
The next middleware we install into our application is an authorization component.
A component might be looking for a specific cookie or accessing a token in the HTTP header.
If the authorization component finds a token, it allows the request to continue.
If not, the authorization component itself may respond to the request with an HTTP error code or redirect the user to the login page.
Otherwise, the authorization component passes the request to the next router's middleware.
A router looks at the URL and determines the next action.
The router is making some responses. If the router does not find any response, the router itself may return a 404 Not Found error.
Case
Now let us understand more about middleware through a simple example. We configure the middleware component by using the Configure method of our startup class.
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo { public class Startup { public Startup() { var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); Configuration = builder.Build(); } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. // Use this method to add services to the container. // For more information on how to configure your application, // visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<startup>(args); } } Configure()方法内,我们将调用IApplicationBuilder接口的扩展方法来添加中间件。</startup>
By default in a new empty project there are two pieces of middleware -
IISPlatformHandler
Middleware registered with app.Run
IISPlatformHandler
IISPlatformHandler allows us to use Windows Authentication. It will look at each incoming request to see if there are any Windows identity related requests and then call the next block middleware.
Middleware registered with app.Run
In this case a middleware is registered with app.Run. The Run method allows us to pass in another method that we can use to handle each response. The Run method is not something you often see, we can call it a middleware terminal.
The middleware you register to run will never have the opportunity to call another middleware. The only thing it can do is receive the request and produce some kind of response.
You also have access to a response object, and you can add some strings to the response object.
If you want to register another middleware after app.Run, this middleware will never be called, because the Run method is the terminal of a middleware. It doesn't call the next block middleware.
How to add a middleware
Let us proceed with the following steps to add another middleware −
Step 1−Right click on the project and select Manage NuGet Packages.
Step 2− Search for Microsoft.aspnet.diagnostics, this particular package contains many different kinds of middleware that we can use.
Step 3−If the package is not installed in your project, then choose to install the package.
Step 4−Now let us call the app.UseWelcomePage middleware in the Configure() method.
// This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseWelcomePage(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); });
Step 5 − Run your application and you will see the following welcome screen.
This welcome screen may not be that useful.
Step 6− Let’s try something else that might be more useful, instead of using the welcome page, we will use the RuntimeInfoPage.
1 // This method gets called by the runtime. 2 // Use this method to configure the HTTP request pipeline. 3 public void Configure(IApplicationBuilder app) { 4 app.UseIISPlatformHandler(); 5 app.UseRuntimeInfoPage(); 6 7 app.Run(async (context) => { 8 var msg = Configuration["message"]; 9 await context.Response.WriteAsync(msg); 10 }); 11 }
Step 7 − Save your Startup.cs page and refresh your browser, you will see the page below.
This RuntimeInfoPage is middleware that will only respond to requests for a specific URL. If the incoming request does not match the URL, this middleware simply passes the request on to the next piece of middleware. The request will go through the IISPlatformHandler middleware and then go to the UseRuntimeInfoPage middleware. It doesn't create a response, so it goes to our application. Run and display the string.
Step 8−We add “runtimeinfo” at the end of the URL. You will now see a page that is runtime information page by the middleware.
You will see a return page, which shows you some information about your runtime environment, such as operating system, runtime version, structure, type and the type you are running. Information about all packages used.
The above is the detailed content of How to set up middleware in asp.net core example tutorial. For more information, please follow other related articles on the PHP Chinese website!

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.