From e984ff3a24bf37a1157314faca2d32a091bb960f Mon Sep 17 00:00:00 2001 From: XuanThuLab Date: Thu, 27 Aug 2020 21:06:19 +0700 Subject: [PATCH] Middleware --- .../02.middleware/.vscode/launch.json | 36 ++++++++ ASP_NET_CORE/02.middleware/.vscode/tasks.json | 42 +++++++++ .../02.middleware/02.middleware.csproj | 8 ++ .../Middleware/CheckAcessMiddleware.cs | 43 ++++++++++ .../Middleware/FrontMiddleware.cs | 24 ++++++ .../Middleware/MyAppExtensions.cs | 13 +++ ASP_NET_CORE/02.middleware/Program.cs | 26 ++++++ .../Properties/launchSettings.json | 27 ++++++ ASP_NET_CORE/02.middleware/Startup.cs | 86 +++++++++++++++++++ .../appsettings.Development.json | 9 ++ ASP_NET_CORE/02.middleware/appsettings.json | 10 +++ ASP_NET_CORE/02.middleware/readme.md | 3 + .../02.middleware/wwwroot/html/test.html | 1 + 13 files changed, 328 insertions(+) create mode 100644 ASP_NET_CORE/02.middleware/.vscode/launch.json create mode 100644 ASP_NET_CORE/02.middleware/.vscode/tasks.json create mode 100644 ASP_NET_CORE/02.middleware/02.middleware.csproj create mode 100644 ASP_NET_CORE/02.middleware/Middleware/CheckAcessMiddleware.cs create mode 100644 ASP_NET_CORE/02.middleware/Middleware/FrontMiddleware.cs create mode 100644 ASP_NET_CORE/02.middleware/Middleware/MyAppExtensions.cs create mode 100644 ASP_NET_CORE/02.middleware/Program.cs create mode 100644 ASP_NET_CORE/02.middleware/Properties/launchSettings.json create mode 100644 ASP_NET_CORE/02.middleware/Startup.cs create mode 100644 ASP_NET_CORE/02.middleware/appsettings.Development.json create mode 100644 ASP_NET_CORE/02.middleware/appsettings.json create mode 100644 ASP_NET_CORE/02.middleware/readme.md create mode 100644 ASP_NET_CORE/02.middleware/wwwroot/html/test.html diff --git a/ASP_NET_CORE/02.middleware/.vscode/launch.json b/ASP_NET_CORE/02.middleware/.vscode/launch.json new file mode 100644 index 0000000..1e9c69a --- /dev/null +++ b/ASP_NET_CORE/02.middleware/.vscode/launch.json @@ -0,0 +1,36 @@ +{ + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "version": "0.2.0", + "configurations": [ + { + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/02.middleware.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}" + } + ] +} \ No newline at end of file diff --git a/ASP_NET_CORE/02.middleware/.vscode/tasks.json b/ASP_NET_CORE/02.middleware/.vscode/tasks.json new file mode 100644 index 0000000..6096e26 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/.vscode/tasks.json @@ -0,0 +1,42 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/02.middleware.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/02.middleware.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "${workspaceFolder}/02.middleware.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/ASP_NET_CORE/02.middleware/02.middleware.csproj b/ASP_NET_CORE/02.middleware/02.middleware.csproj new file mode 100644 index 0000000..7f3aa79 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/02.middleware.csproj @@ -0,0 +1,8 @@ + + + + netcoreapp3.1 + _02.middleware + + + diff --git a/ASP_NET_CORE/02.middleware/Middleware/CheckAcessMiddleware.cs b/ASP_NET_CORE/02.middleware/Middleware/CheckAcessMiddleware.cs new file mode 100644 index 0000000..27379b1 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Middleware/CheckAcessMiddleware.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace _02.middleware { + public class CheckAcessMiddleware { + // Lưu middlewware tiếp theo trong Pipeline + private readonly RequestDelegate _next; + public CheckAcessMiddleware (RequestDelegate next) => _next = next; + public async Task Invoke (HttpContext httpContext) { + if (httpContext.Request.Path == "/testxxx") { + + Console.WriteLine ("CheckAcessMiddleware: Cấm truy cập"); + await Task.Run ( + async () => { + string html = "

CAM KHONG DUOC TRUY CAP

"; + httpContext.Response.StatusCode = StatusCodes.Status403Forbidden; + await httpContext.Response.WriteAsync (html); + } + ); + + } else { + + // Thiết lập Header cho HttpResponse + httpContext.Response.Headers.Add ("throughCheckAcessMiddleware", new [] { DateTime.Now.ToString () }); + + Console.WriteLine ("CheckAcessMiddleware: Cho truy cập"); + + // Chuyển Middleware tiếp theo trong pipeline + await _next (httpContext); + + } + + } + } + +} \ No newline at end of file diff --git a/ASP_NET_CORE/02.middleware/Middleware/FrontMiddleware.cs b/ASP_NET_CORE/02.middleware/Middleware/FrontMiddleware.cs new file mode 100644 index 0000000..1e9b369 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Middleware/FrontMiddleware.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace _02.middleware { + public class FrontMiddleware : IMiddleware + { + public async Task InvokeAsync(HttpContext context, RequestDelegate next) + { + Console.Clear(); + Console.WriteLine("FrontMiddleware: " + context.Request.Path); + context.Items.Add("dulieu1", "Data Object ..."); + + await next(context); + } + } +} + diff --git a/ASP_NET_CORE/02.middleware/Middleware/MyAppExtensions.cs b/ASP_NET_CORE/02.middleware/Middleware/MyAppExtensions.cs new file mode 100644 index 0000000..6e98252 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Middleware/MyAppExtensions.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Builder; + +namespace _02.middleware +{ + public static class MyAppExtensions + { + // Mở rộng cho IApplicationBuilder phương thức UseCheckAccess + public static IApplicationBuilder UseCheckAccess(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } +} diff --git a/ASP_NET_CORE/02.middleware/Program.cs b/ASP_NET_CORE/02.middleware/Program.cs new file mode 100644 index 0000000..406bd84 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Program.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace _02.middleware +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/ASP_NET_CORE/02.middleware/Properties/launchSettings.json b/ASP_NET_CORE/02.middleware/Properties/launchSettings.json new file mode 100644 index 0000000..301e75e --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:29289", + "sslPort": 44349 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "_02.middleware": { + "commandName": "Project", + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ASP_NET_CORE/02.middleware/Startup.cs b/ASP_NET_CORE/02.middleware/Startup.cs new file mode 100644 index 0000000..999d761 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/Startup.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace _02.middleware +{ + public class Startup + { + + // Đăng ký các dịch vụ sử dụng bởi ứng dụng, services là một DI container + // Xem: https://xuanthulab.net/dependency-injection-di-trong-c-voi-servicecollection.html + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(); + services.AddDistributedMemoryCache(); // Thêm dịch vụ dùng bộ nhớ lưu cache (session sử dụng dịch vụ này) + services.AddSession(); // Thêm dịch vụ Session, dịch vụ này cunng cấp Middleware: SessionMiddleware + } + + + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + + app.UseAuthentication + + app.UseMiddleware(); + + + // Thêm StaticFileMiddleware - nếu Request là yêu cầu truy cập file tĩnh, + // Nó trả ngay về Response nội dung file và là điểm cuối pipeline, nếu khác + // nó gọi Middleware phía sau trong Pipeline + app.UseStaticFiles(); + + + // Thêm SessionMiddleware: khôi phục, thiết lập - tạo ra session + // gán context.Session, sau đó chuyển gọi ngay middleware + // tiếp trong pipeline + app.UseSession(); + + // Thêm middleware - CheckAccessMiddleware + app.UseCheckAccess(); + + + // Thêm EndpointRoutingMiddleware: ánh xạ Request gọi đến Endpoint (Middleware cuối) + // phù hợp định nghĩa bởi EndpointMiddleware + app.UseRouting(); + + // app.UseEndpoint dùng để xây dựng các endpoint - điểm cuối của pipeline theo Url truy cập + app.UseEndpoints(endpoints => + { + + // EndPoint(2) khi truy vấn đến /Testpost với phương thức post hoặc put + endpoints.MapMethods("/Testpost" , new string[] {"post", "put"}, async context => { + context.Session.SetInt32("count", 1); + await context.Response.WriteAsync("post/pust"); + }); + + // EndPoint(2) - Middleware khi truy cập /Home với phương thức GET - nó làm Middleware cuối Pipeline + endpoints.MapGet("/Home", async context => { + + int? count = context.Session.GetInt32("count"); + count = (count != null) ? count + 1 : 1; + context.Session.SetInt32("count", count.Value); + await context.Response.WriteAsync($"Home page! {count}"); + + }); + }); + + // EndPoint(3) app.Run tham số là hàm delegate tham số là HttpContex + // - nó tạo điểm cuối của pipeline. + app.Run(async context => { + context.Response.StatusCode = StatusCodes.Status404NotFound; + context.Session.SetInt32("count", 1); + + await context.Response.WriteAsync("Page not found"); + }); + + + } + } +} diff --git a/ASP_NET_CORE/02.middleware/appsettings.Development.json b/ASP_NET_CORE/02.middleware/appsettings.Development.json new file mode 100644 index 0000000..8983e0f --- /dev/null +++ b/ASP_NET_CORE/02.middleware/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + } +} diff --git a/ASP_NET_CORE/02.middleware/appsettings.json b/ASP_NET_CORE/02.middleware/appsettings.json new file mode 100644 index 0000000..d9d9a9b --- /dev/null +++ b/ASP_NET_CORE/02.middleware/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/ASP_NET_CORE/02.middleware/readme.md b/ASP_NET_CORE/02.middleware/readme.md new file mode 100644 index 0000000..fb5a3a1 --- /dev/null +++ b/ASP_NET_CORE/02.middleware/readme.md @@ -0,0 +1,3 @@ +# (ASP.NET Core) Tạo middleware và đăng ký vào pipeline của ứng dụng Web C# CSharp + +https://xuanthulab.net/asp-net-core-tao-middleware-va-dang-ky-vao-pipeline-cua-ung-dung-web-c-csharp.html#transferdata \ No newline at end of file diff --git a/ASP_NET_CORE/02.middleware/wwwroot/html/test.html b/ASP_NET_CORE/02.middleware/wwwroot/html/test.html new file mode 100644 index 0000000..7e263be --- /dev/null +++ b/ASP_NET_CORE/02.middleware/wwwroot/html/test.html @@ -0,0 +1 @@ +Static file \ No newline at end of file