From 64b33493936b34a5dd8ce6a23ccc5376a84294a8 Mon Sep 17 00:00:00 2001 From: Young Date: Sun, 29 Sep 2024 21:58:14 +0800 Subject: [PATCH] added not found middleware and unit test --- .../Infrastructure.Tests.csproj | 5 ++++ src/Infrastructure.Tests/MiddlewareTests.cs | 26 +++++++++++++++++++ .../Middlewares/NotFoundMiddleware.cs | 21 +++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 src/Infrastructure.Tests/MiddlewareTests.cs create mode 100644 src/Infrastructure/Middlewares/NotFoundMiddleware.cs diff --git a/src/Infrastructure.Tests/Infrastructure.Tests.csproj b/src/Infrastructure.Tests/Infrastructure.Tests.csproj index 9d57ba6..7aae03d 100644 --- a/src/Infrastructure.Tests/Infrastructure.Tests.csproj +++ b/src/Infrastructure.Tests/Infrastructure.Tests.csproj @@ -14,6 +14,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -26,4 +27,8 @@ + + + + diff --git a/src/Infrastructure.Tests/MiddlewareTests.cs b/src/Infrastructure.Tests/MiddlewareTests.cs new file mode 100644 index 0000000..ff87a97 --- /dev/null +++ b/src/Infrastructure.Tests/MiddlewareTests.cs @@ -0,0 +1,26 @@ +using System.Net; +using Infrastructure.Middlewares; +using Infrastructure.Utils; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Hosting; + +namespace Infrastructure.Tests; + +public class MiddlewareTests +{ + [Fact] + public async Task NotFoundMiddlewareShouldReturn404() + { + using var host = await new HostBuilder().ConfigureWebHost(builder => + { + builder.UseTestServer().Configure(app => { app.UseMiddleware(); }); + }).StartAsync(); + var response = await host.GetTestClient().GetAsync("/404"); + var content = await response.Content.ReadAsStringAsync(); + var message = content.Deserialize(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(HttpStatusCode.NotFound.GetHashCode(), message.Code); + } +} \ No newline at end of file diff --git a/src/Infrastructure/Middlewares/NotFoundMiddleware.cs b/src/Infrastructure/Middlewares/NotFoundMiddleware.cs new file mode 100644 index 0000000..1c80c93 --- /dev/null +++ b/src/Infrastructure/Middlewares/NotFoundMiddleware.cs @@ -0,0 +1,21 @@ +using Infrastructure.Utils; +using Microsoft.AspNetCore.Http; + +namespace Infrastructure.Middlewares; + +public class NotFoundMiddleware(RequestDelegate next) +{ + public async Task InvokeAsync(HttpContext context) + { + await next(context); + + if (context.Response.StatusCode == StatusCodes.Status404NotFound) + { + var path = context.Request.Path.Value; + var message=new MessageData(false,$"request path: {path} not found",404); + context.Response.ContentType = "application/json"; + context.Response.StatusCode = StatusCodes.Status200OK; + await context.Response.WriteAsync(message.Serialize()); + } + } +} \ No newline at end of file