ASP.NET Core middleware setting tutorial (7)_Practical tips
This article mainly introduces the setting tutorial of ASP.NET Coremiddleware in detail. It has certain reference value. Interested friends can refer to it
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 access 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
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); } }
In the Configure() method, we will call the extension method of the IApplicationBuilder interface to add middleware.
By default, there are two pieces of middleware in a new empty project -
IISPlatformHandler
Middleware registered with app.Run
IISPlatformHandler
IISPlatformHandler allows us to use Windows Authentication. It will look at each incoming request, 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 Click on the project and select Manage NuGet Packages.
Step 2−Search 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.
步骤6−让我们试试别的东西,可能是更有用的,而不是使用欢迎页面,我们将使用RuntimeInfoPage。
// This method gets called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseRuntimeInfoPage(); app.Run(async (context) => { var msg = Configuration["message"]; await context.Response.WriteAsync(msg); }); }
第 7 步 − 保存您的 Startup.cs 页面并刷新您的浏览器,你会看到下面的页面。
这个 RuntimeInfoPage 是中间件,将只响应一个特定的 URL 的请求。如果传入的请求与该 URL 不匹配,这个中间件只是让请求传递到下一件中间件。该请求将通过 IISPlatformHandler 中间件,然后转到 UseRuntimeInfoPage 中间件。它不会创建响应,所以它会转到我们的应用程序。运行并显示该字符串。
步骤8−我们在URL结尾添加“ runtimeinfo”。现在,您将看到一个页面,该页面是由中间件运行时信息页面。
你将看到一个返回页面,它给你展示了一些关于你的运行时环境,如操作系统、运行时版本,结构,类型和您正在使用的所有包的信息。
The above is the detailed content of ASP.NET Core middleware setting tutorial (7)_Practical tips. 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

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

Dreamweaver Mac version
Visual web development tools