{"id":1051,"date":"2022-04-09T12:38:05","date_gmt":"2022-04-09T04:38:05","guid":{"rendered":"http:\/\/www.wayln.com\/?p=1051"},"modified":"2022-04-18T22:56:02","modified_gmt":"2022-04-18T14:56:02","slug":"%e4%b8%ad%e9%97%b4%e4%bb%b6","status":"publish","type":"post","link":"https:\/\/www.wayln.com\/?p=1051","title":{"rendered":"Middleware and Service"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_transparent no_bullets\"><p class=\"toc_title\">Contents<\/p><ul class=\"toc_list\"><li><a href=\"#i\"><span class=\"toc_number toc_depth_1\">1<\/span> \u521b\u5efa\u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef6<\/a><ul><li><a href=\"#i-2\"><span class=\"toc_number toc_depth_2\">1.1<\/span> \u521b\u5efa\u81ea\u5b9a\u4e49\u7c7b\u4e2d\u95f4\u4ef6<\/a><\/li><li><a href=\"#Understanding_the_Return_Pipeline_Path\"><span class=\"toc_number toc_depth_2\">1.2<\/span> Understanding the Return Pipeline Path<\/a><\/li><li><a href=\"#Useful_HttpContext_Members\"><span class=\"toc_number toc_depth_2\">1.3<\/span> Useful HttpContext Members<\/a><\/li><li><a href=\"#Useful_HttpRequest_Members\"><span class=\"toc_number toc_depth_2\">1.4<\/span> Useful HttpRequest Members<\/a><\/li><li><a href=\"#Useful_HttpResponse_Members\"><span class=\"toc_number toc_depth_2\">1.5<\/span> Useful HttpResponse Members<\/a><\/li><li><a href=\"#short_circuiting_the_request_pipeline\"><span class=\"toc_number toc_depth_2\">1.6<\/span> short circuiting the request pipeline<\/a><\/li><li><a href=\"#Creating_Pipeline_Branches\"><span class=\"toc_number toc_depth_2\">1.7<\/span> Creating Pipeline Branches<\/a><\/li><\/ul><\/li><li><a href=\"#Services\"><span class=\"toc_number toc_depth_1\">2<\/span> Services<\/a><\/li><\/ul><\/div>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_57a15554c29b0df6306c3fec560be77e.jpg\"><img decoding=\"async\" src=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_57a15554c29b0df6306c3fec560be77e.jpg\" alt=\"\" \/><\/a><br \/>\nThe purpose of the ASP.NET Core platform is to receive HTTP requests and send reposes to them,which ASP.NET Core delegates to middleware components. Middleware component are arranged in a chain,known as the request pipeline.<\/p>\n<pre><code class=\"language-CSharp line-numbers\">  public class Startup\n    {\n        \/\/ This method gets called by the runtime. Use this method to add services to the container.\n        \/\/ For more information on how to configure your application, visit https:\/\/go.microsoft.com\/fwlink\/?LinkID=398940\n        public void ConfigureServices(IServiceCollection services)\n        {\n        }\n\n        \/\/ This method gets called by the runtime. Use this method to configure the HTTP request pipeline.\n        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,ILogger&lt;Startup&gt; logger)\n        {\n            logger.LogInformation(\"\u5f00\u59cb\u8bb0\u5f55\u3002\u3002\u3002\u3002\");\n            if (env.IsDevelopment())\n            {\n                app.UseDeveloperExceptionPage();\n            }\n\n            app.UseRouting();\n            app.Use(next =&gt;\n            {\n                return async httpContext =&gt;\n                {\n                    if (httpContext.Request.Path.StartsWithSegments(\"\/first\"))\n                    {\n                        logger.LogInformation(\"\u5f00\u59cb\u8bb0\u5f551\u3002\u3002\u3002\u3002\");\n                        await httpContext.Response.WriteAsync(\"First!!!\");\n                    }\n                    else\n                    {\n                        logger.LogInformation(\"\u5f00\u59cb\u8bb0\u5f552\u3002\u3002\u3002\u3002\");\n                        await next(httpContext);\n                    }\n\n                };\n            });\n\n            app.UseEndpoints(endpoints =&gt;\n            {\n                endpoints.MapGet(\"\/\", async context =&gt;\n                {\n                    logger.LogInformation(\"\u5f00\u59cb\u8bb0\u5f553\u3002\u3002\u3002\u3002\");\n                    await context.Response.WriteAsync(\"Hello World!\");\n                });\n            });\n        }\n    }\n<\/code><\/pre>\n<p>\u53ef\u4ee5\u5728ConfigureServices(IServiceCollection services)\u4e2d\u914d\u7f6e\u6ce8\u518c\u670d\u52a1<br \/>\n&#8211; services.AddMvc();<br \/>\n\u6dfb\u52a0MVC\u670d\u52a1<\/p>\n<p>\u53ef\u4ee5\u5728public void Configure(IApplicationBuilder app, IWebHostEnvironment env)\u4e2d\u914d\u7f6e\u4e2d\u95f4\u4ef6\uff0c\u4ee5\u53ca\u6ce8\u5165\u65e5\u5fd7\u7b49<br \/>\nIWebHostEnvironment env\u53ef\u4ee5\u83b7\u53d6\u5f53\u524d\u7684\u73af\u5883\u662f\u5f00\u53d1\u73af\u5883\u8fd8\u662f\u751f\u4ea7\u73af\u5883\u8fd8\u662f\u9884\u89c8\u6f14\u793a\u73af\u5883<br \/>\n&#8211; app.UseWelcomePage()<br \/>\n\u663e\u793a\u6b22\u8fce\u9875<br \/>\n&#8211; app.use()<\/p>\n<pre><code class=\"language-CSharp line-numbers\">IApplicationBuilder Use(Func&lt;RequestDelegate, RequestDelegate&gt; middleware);\n\n public delegate Task RequestDelegate(HttpContext context);\n<\/code><\/pre>\n<pre><code class=\"language-CSharp line-numbers\">          app.Use(next =&gt;\n            {\n                return async httpContext =&gt;\n                {\n                    if (httpContext.Request.Path.StartsWithSegments(\"\/first\"))\n                    {\n                        await httpContext.Response.WriteAsync(\"First!!!\");\n                    }\n                    else\n                    {\n                        await next(httpContext);\n                    }\n\n                };\n            });\n<\/code><\/pre>\n<ul>\n<li>app.UseDeveloperExceptionPage();<br \/>\n\u4f1a\u663e\u793a\u5f02\u5e38\u9875\u9762\uff0c\u8981\u653e\u5728\u7ba1\u9053\u4e2d\u6bd4\u8f83\u9760\u524d\u7684\u4f4d\u7f6e<\/li>\n<li>app.useDefaultFiles()<br \/>\n\u53ef\u4ee5\u4f7f\u7528\u8be5\u4e2d\u95f4\u4ef6\u8bbe\u7f6e\u6307\u5b9a\u7684\u9ed8\u8ba4\u6587\u4ef6\uff0c\u7136\u540e\u5c06\u9ed8\u8ba4\u7684\u6587\u4ef6\u5728\u901a\u8fc7appUseStaticFiles() \u8fd4\u56de\uff0c\u6240\u4ee5\u4e2d\u95f4\u4ef6\u7684\u987a\u5e8f\u5f88\u91cd\u8981<\/li>\n<li>app.UseStaticFiles()<br \/>\n\u4f7f\u7528wwwroot\u4e2d\u7684\u9759\u6001\u9875\u9762\u6216\u6587\u4ef6<\/li>\n<li>app.UseFileServer()<br \/>\n\u5305\u542b\u4e0a\u9762\u4e24\u4e2a\u4e2d\u95f4\u4ef6\u529f\u80fd\uff0c\u8fd8\u53ef\u4ee5\u5305\u542b\u76ee\u5f55\u6d4f\u89c8\u529f\u80fd<\/li>\n<li>app.UseMvcWithDefaultRoute()<br \/>\n\u4f7f\u7528\u9ed8\u8ba4\u8def\u7531\u7684MVC\u4e2d\u95f4\u4ef6<\/li>\n<\/ul>\n<h1><span id=\"i\">\u521b\u5efa\u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef6<\/span><\/h1>\n<pre><code class=\"language-CSharp line-numbers\">app.Use(async (context,next)=&gt;{\n    if(context.Request.Method==HttpMethods.Get &amp;&amp; context.Request.Query[\"custom\"]==\"true\"){\n        context.Reponse.ContextType=\"text\/plain\";\n        await context.Response.WriteAsync(\"Custom Middleware \\n\");\n    }\n    await next();\n});\n<\/code><\/pre>\n<h2><span id=\"i-2\">\u521b\u5efa\u81ea\u5b9a\u4e49\u7c7b\u4e2d\u95f4\u4ef6<\/span><\/h2>\n<pre><code class=\"language-Charp line-numbers\">namespace Platform\n{\n    public class QueryStringMiddleWare\n    {\n        private RequestDelegate next;\n        public QueryStringMiddleWare(RequestDelegate nextDelegate)\n        {\n            next=nextDelegate;\n        }\n        public async Task  Invoke(HttpContext context)\n        {\n            if(context.Request.Method==HttpMethods.Get &amp;&amp; context.Request.Query[\"custom\"]==\"true\")\n            {\n                if(!context.Response.HasStarted)\n                {\n                    context.Response.ContentType=\"text\/plain\";\n\n                }\n                await context.Response.WriteAsync(\"Class-based Middleware \\n\");\n            }\n            await next(context);\n        }\n\n    }\n}\n````\n\n## \u4f7f\u7528\u7c7b\u4e2d\u95f4\u4ef6\n```CSharp\napp.UseMiddleware&lt;Platform.QueryStringMiddleWare&gt;();\n<\/code><\/pre>\n<h2><span id=\"Understanding_the_Return_Pipeline_Path\">Understanding the Return Pipeline Path<\/span><\/h2>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_2f8200c1f401622eabb328b13e1ed756.jpg\"><img decoding=\"async\" src=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_2f8200c1f401622eabb328b13e1ed756.jpg\" alt=\"\" \/><\/a><\/p>\n<pre><code class=\"language-CSharp line-numbers\">app.Use(async (context,next)=&gt;{\n    await next();\n    await context.Response.WriteAsync($\"\\n Status Code:{context.Response.StatusCode}\");\n});\n<\/code><\/pre>\n<h2><span id=\"Useful_HttpContext_Members\">Useful HttpContext Members<\/span><\/h2>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Descirption<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Connection<\/td>\n<td>This property returns a ConnectionInfo object that provides information about the network connection underlying the HTTP request,including details of local and remote IP address and ports<\/td>\n<\/tr>\n<tr>\n<td>Request<\/td>\n<td>This property returns an HttpResponse object that is used to create a response to the HTTP request<\/td>\n<\/tr>\n<tr>\n<td>Session<\/td>\n<td>This property returns the session data associated with the request.<\/td>\n<\/tr>\n<tr>\n<td>User<\/td>\n<td>This property returns details of the user associated with the request<\/td>\n<\/tr>\n<tr>\n<td>Features<\/td>\n<td>This property provides access to request features,which allow access to the low-level aspects of request handing<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2><span id=\"Useful_HttpRequest_Members\">Useful HttpRequest Members<\/span><\/h2>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Body<\/td>\n<td>This property returns a stream that can be used to read the request body<\/td>\n<\/tr>\n<tr>\n<td>ContentLength<\/td>\n<td>returns the value of the Content-Length header<\/td>\n<\/tr>\n<tr>\n<td>ContentType<\/td>\n<td>return the value of the content-Type header<\/td>\n<\/tr>\n<tr>\n<td>Cookies<\/td>\n<td>returns the request cookies<\/td>\n<\/tr>\n<tr>\n<td>Form<\/td>\n<td>returns a representation of the request body as a form<\/td>\n<\/tr>\n<tr>\n<td>Headers<\/td>\n<td>return the request headers<\/td>\n<\/tr>\n<tr>\n<td>IsHttps<\/td>\n<td>returns true if the request was made using HTTPS<\/td>\n<\/tr>\n<tr>\n<td>Method<\/td>\n<td>returns the HTTP verb-also known as the HTTP method-used for the request<\/td>\n<\/tr>\n<tr>\n<td>Path<\/td>\n<td>returns the path section of the request URL<\/td>\n<\/tr>\n<tr>\n<td>Query<\/td>\n<td>returns the query string section of the request URL as key-value pairs<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2><span id=\"Useful_HttpResponse_Members\">Useful HttpResponse Members<\/span><\/h2>\n<table>\n<thead>\n<tr>\n<th>Name<\/th>\n<th>Description<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>contentLength<\/td>\n<td>sets the value of the Content-Length header<\/td>\n<\/tr>\n<tr>\n<td>ContentType<\/td>\n<td>sets the value of the Content-Type header<\/td>\n<\/tr>\n<tr>\n<td>Cookies<\/td>\n<td>allows cookies to be associated with the request<\/td>\n<\/tr>\n<tr>\n<td>HasStarted<\/td>\n<td>returns true if ASP.NET Core has started to send the response headers to the client,after which it is not possible to make changes to the status code or headers<\/td>\n<\/tr>\n<tr>\n<td>Headers<\/td>\n<td>allows the response headers to be set<\/td>\n<\/tr>\n<tr>\n<td>StatusCode<\/td>\n<td>sets the status code for the response<\/td>\n<\/tr>\n<tr>\n<td>WriteAsync(data)<\/td>\n<td>this asynchronous method writes a data string to the response body<\/td>\n<\/tr>\n<tr>\n<td>Redirect(url)<\/td>\n<td>sends a redirection response<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2><span id=\"short_circuiting_the_request_pipeline\">short circuiting the request pipeline<\/span><\/h2>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_52284f0c1cee3f2d72cbbcf241ae5d2c.jpg\"><img decoding=\"async\" src=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_52284f0c1cee3f2d72cbbcf241ae5d2c.jpg\" alt=\"\" \/><\/a><\/p>\n<h2><span id=\"Creating_Pipeline_Branches\">Creating Pipeline Branches<\/span><\/h2>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_a7a1ad7cfab221d94db80660da3857f8.jpg\"><img decoding=\"async\" src=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_a7a1ad7cfab221d94db80660da3857f8.jpg\" alt=\"\" \/><\/a><\/p>\n<h1><span id=\"Services\">Services<\/span><\/h1>\n<p>Services are object that provide features in a web application.Any calss can be used as a service.they are managed by ASP.NET Core,and a feature called dependency injection makes it possible to easily access service anywhere<\/p>\n<p><a class=\"wp-editor-md-post-content-link\" href=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_34c0ad857d55fc118b6c92875a2d8470.jpg\"><img decoding=\"async\" src=\"http:\/\/www.wayln.com\/wp-content\/uploads\/2022\/04\/wp_editor_md_34c0ad857d55fc118b6c92875a2d8470.jpg\" alt=\"\" \/><\/a><\/p>\n<p>middleware components use only the services they require to do theri work.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Contents1 \u521b\u5efa\u81ea\u5b9a\u4e49\u4e2d\u95f4\u4ef61.1 \u521b\u5efa\u81ea\u5b9a\u4e49\u7c7b\u4e2d\u95f4\u4ef61.2 Understanding the Re [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[44,4,2],"tags":[],"class_list":["post-1051","post","type-post","status-publish","format-standard","hentry","category-asp-net-core","category-c","category-2"],"_links":{"self":[{"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/posts\/1051","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wayln.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1051"}],"version-history":[{"count":19,"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/posts\/1051\/revisions"}],"predecessor-version":[{"id":1153,"href":"https:\/\/www.wayln.com\/index.php?rest_route=\/wp\/v2\/posts\/1051\/revisions\/1153"}],"wp:attachment":[{"href":"https:\/\/www.wayln.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1051"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wayln.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1051"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wayln.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1051"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}