Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is ASP.Net Core MVC middleware?

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "what is ASP.Net Core MVC middleware". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

When talking about middleware, we are actually talking about the ConfigureServices and Configure methods in the Startup class.

In the program startup class Program, we call the UseStartup method in the CreateWebHostBuilder method, which injects the Startup class with generics, and the program automatically instantiates the class and executes the ConfigureServices and Configure methods in it. We can do a lot of configuration operations.

The first method to call is, of course, the constructor, there is no, we won't say, and then the ConfigureServices method. This method has been used in the previous section, in which we can register some services or we call custom services. After registering for the services, we can use them elsewhere through Einai injection.

The method that is then executed is the Configure method. We can see that the default first parameter of the Configure method is the IApplicationBuilder interface, which can be understood as the root of the whole program. Through this interface object, we can accurately configure and enable our middleware to combine our various middleware to form a perfect Web application to process our HTTP requests and make corresponding responses, and so on.

Before we talk about it, let's put

If (env.IsDevelopment ()) {app.UseDeveloperExceptionPage ();}

Comment out these lines of code and use them later to explain what this is for and why you need to add an if. Comment it out here first.

Let's look at this code.

App.Run (async (context) = > {var msg = welcome.GetWelcomMsg (); await context.Response.WriteAsync (msg);})

This app.Run method can be understood as a middleware written by ourselves, which does nothing but output a string for the response. In fact, this is the default generation of the new project.

In a real project, we basically don't use app.Run to process our requests, because what I do is much more complicated than outputting a string.

In actual development, the middleware we usually use starts with app.Usexxxx in order to form a completed Web project, such as app.UseMvc / app.UseStaticFiles and so on, to enable the system's own middleware to obtain other third-party middleware.

Let's enable an egg middleware that comes with ASP.Net Core MVC, code: app.UseWelcomePage (); enable the default MVC welcome page. We implement F 5.

We can normally see that a page appears instead of a simple string output.

Then we try to change the address bar and write anything. We can find that no matter how we enter the address, we go to the welcome page, as shown in the figure:

At this point, we can find that the "priority" of this "egg" middleware is still very high. When ASP.Net Core MVC finds that you are using this middleware, he will not execute the following things, or will not execute the latter middleware.

In addition, when we use middleware, or when we call the app.Usexxxx method, generally speaking, this method will accept an object parameter, which can be configured for this middleware. Let's try to configure the "egg" middleware and tell us how to configure the middleware. The code goes like this.

App.UseWelcomePage (new WelcomePageOptions {Path = "/ welcome"})

As you can see, here is an address (path) configured for the "colored egg". Now let's see the effect of F5.

We will find that the output of the web page is a string, so if we add / welcome after the address, we can find that the "colored egg" can appear normally, indicating that this configuration is valid.

Of course, my purpose is not to talk about how to use this "colored egg", but to show you how to use and configure middleware. Basically, all middleware are used and configured in this way.

Now that we've come to this point, let's talk about app.Use. How to say this method, that is, it is relatively "low-level", because the parameter type in app.Use is RequestDelegate, that is, the delegate of the current request object, which is relatively "low-level" and can be said to be the "prototype" of the current request pipeline. Let's try to write some code.

App.Use (next = > {return async context = > {if (context.Request.Path.StartsWithSegments ("/ first")) {await context.Response.WriteAsync ("First");} else {await next (context);}};})

The code we wrote is like the above, which means: when the current address is / first, output the string First, otherwise, let's go ahead and execute other middleware, and we'll run it to see the effect. As you can see, the default output is Hello, .net Core 2.2.2.When we add / first to the address, the output is First, as shown in the figure:

When we enter the address / welcome, we can see that the "colored egg" appears normally, and we can see that our Use method is normal.

In the actual development process, we rarely use the app.Use method to deal with our underlying requests directly. Here is just a brief introduction to this method and what it can do.

If you know what app.Use does, delete or comment out the above app.Use method. We won't use it in the following tutorial.

Next, let's do something bad. We manually report an exception in the app.Run method. The code is as follows:

App.Run (async (context) = > {throw new Exception (); var msg = welcome.GetWelcomMsg (); await context.Response.WriteAsync (msg);})

When we execute the project, we will see a 500th error. This is the case with Chrome browsers. Other browsers may be different.

But we don't want this. We hope we can see the details of the exception. At this point, we need to enable an exception middleware, that is, the code of iif (env.IsDevelopment ()) that we commented out above. If we enable it, then the code in our Configure method looks like this, as shown in the figure:

Then we run the project on F5, and that's what it looks like, as shown in the figure:

Our abnormality is obvious, so it's good to troubleshoot errors.

As for why to add if (env.IsDevelopment ()), the meaning of this code is clear at a glance, that is, the exception display middleware is enabled only when the current environment is the development environment.

Because we only want to display abnormal details during development or debugging, but not in other environments, so it is safer. If we do not add this if, detailed error messages will be displayed in any environment, which may bring security risks to our Web applications.

So, let's add an else and enable another middleware in else, as follows:

If (env.IsDevelopment ()) {app.UseDeveloperExceptionPage ();} else {app.UseExceptionHandler ();}

In this way, when we are not in the development environment, sending exceptions is like this:

So as not to expose some sensitive information

We find that the code that starts the exception page middleware is written at the top, so what happens if we move it to the end of the Configure method? Let's give it a try. The code is shown below:

As you can see, I moved the exception page middleware to the last enabled, we F5 run the project, we will find that the browser is not the first exception page, but directly 500 errors.

As you can know, the enabling order of middleware is based on Nai relationship and order, and can not be enabled casually. You need to enable the corresponding middleware in the right place. If the order is wrong, it may lead to middleware failure. If you are in the development process, enable a certain middleware, but it has no effect, you can use this idea for troubleshooting.

This is the end of this section, so far, our Web application function is very simple, is to output a string and enable a "colored egg".

We also talked about the "environment". For example, if (env.IsDevelopment ()) above determines whether it is a development environment, so how to change this environment, let's switch between the development or commissioning and operation environment, load different configurations and enable different middleware.

This is the end of the content of "what is ASP.Net Core MVC middleware". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report