How "ASP. NET Core" hides "Kestrel" in the response header

Source: Internet
Author: User

The entire universe knows that the ASP. NET Core application is independent of server components, so it can run on its own, typically using a Kestrel server that supports cross-platform (of course, you can also consider using Httpsys on Windows, but run as an administrator).

Although it is recommended in the SDK documentation that we use the server component to "reverse" the proxy, running independently is also allowed. When the Web application runs independently, the client makes a request and, in the HTTP message of the response, attaches a Server header whose value is Kestrel. As shown in the following HD uncensored no watermark.

See, Server = Kestrel. The above old week made a small station, and is running independently, but I want to hide that Kestrel name, want to change it to Pig Platform. Now that you think about it, then do it, this is actually very good, as long as the middleware in the HTTP pipeline to insert a custom middleware, modify the Server header on the line.

The implementation method is to use the Configure method of the Startup class.

         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app.            Usedeveloperexceptionpage (); } App. Use (  Async (context, next) = {context. response.headers["server"] = "Bun Server 2098" ;  await  next (); }); App.        Usemvc (); }

Because the code is not much, there is no need to write the middleware class, direct use method to transfer the delegate is OK. The code is the simplest of all the universe, but you have to pay attention to the order, what do you mean, like me instead.

            App. Use (async (context, next) =            {                await  next (); Context. response.headers["server""Bun server 2098" ;            });

This will make an error, because next directly into the next middleware, and this "next" middleware may be MVC, when the HTTP header set is locked, become read-only, a modification error. So, to get rid of the Server header before entering the next middleware.

So it's not going to go wrong.

                Context. response.headers["server""Bun server 2098";                 await next ();

When this is done, the Server header becomes the same when the client accesses it.

The effect is done, but, in this way, our startup.configure method seems to be less concise. Moreover, this code is not enough to force lattice, seriously does not meet the current young people are keen to pretend the times demand.

We can use Starup Filter in order to adapt it to the spirit of the zeitgeist, which is loaded with force.

Look at the name you will guess, is a filter, its role is: the middleware can be inserted into the HTTP message pipeline in the front, or the last side. The way to implement the Filter is to implement the Istartupfilter interface. There is only one method for this interface.

  Action<iapplicationbuilder> Configure (action<iapplicationbuilder> next);

This method is similar to the Configure method in the Startup class. Both the parameter and the return value are a delegate with the Iapplicationbuilder parameter. The next parameter of the method is the next Configure method to be executed, possibly the Configure method of the next startup Filter, or the Configure method of the startup class. The return value is our handling of the current Configure method.

Take a look at my implementation first.

     Public classMystartupfilter:istartupfilter { PublicAction<iapplicationbuilder> Configure (action<iapplicationbuilder>next) {            returnApp ={app. Use (Async(context, _next) ={context. RESPONSE.HEADERS.ADD ("Server","Big Server"); await_next ();              });            next (app);        }; }    }

In this project, except for the inside of the runtime, the externally implemented Starup Filter has only one--mystartupfilter, so in the Configure method, the parameter next is the Configure method of the Startup class. So here, you can decide whether the application executes the Configure method in the Startup class.

The above code means: first register our own middleware (here is the delegate) for the application, modify the Server HTTP header, and then call the Configure method in the Startup class. This allows our custom middleware code to be placed in front of the entire HTTP message pipeline.

At this point, you can delete the code just written in the Startup class and use the Configure method to keep it simple.

         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app.            Usedeveloperexceptionpage (); }            //app. Use (Async (context, next) =//{            //context.            response.headers["server"] = "Bun Server 2098"; //await next (); //});app.        Usemvc (); }

So how does this Startup Filter class work, as if there is no associated API added. In fact, ASP. NET Core has a universal rule--dependency injection. When any extension type you write yourself doesn't know how to use it, you just put it in the servicecollection. Therefore, you can modify the Configureservices method of the Starup class.

         Public void configureservices (iservicecollection services)        {            services. Addmvc (). Withrazorpagesatcontentroot (). Addrazorpagesoptions (o= =            {                o.conventions.addpageroute ("/main  """);            });           Services. AddTransient<istartupfilter, mystartupfilter>();        }

Servicecollection has three Add methods, the same use, different is the life cycle of the object instance.

1, Addsingleton: Live the longest, Shou and Tian Qi. It produces only one instance in the entire application.

2, addscoped: Life is slightly short, it is mainly in the same HTTP request in effect, from the HTTP request to create an instance, after the request is finished destroying the instance.

3, AddTransient: This is the most short-lived, use the time to create an instance, run out and throw.

Our Startup Filter is used only once when the application is initialized, and is no longer used, so the AddTransient method is used to add the line, the whole application is used once, there is no need to occupy the position.

At this point, access to the server, you can also change the default Kestrel.

The same effect.

Well, that's what's going on here today, it's not much of a tall trick.

How "ASP. NET Core" hides "Kestrel" in the response header

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.