parent
254ce7e42e
commit
64b3349393
@ -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<NotFoundMiddleware>(); });
|
||||||
|
}).StartAsync();
|
||||||
|
var response = await host.GetTestClient().GetAsync("/404");
|
||||||
|
var content = await response.Content.ReadAsStringAsync();
|
||||||
|
var message = content.Deserialize<MessageData>();
|
||||||
|
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||||
|
Assert.Equal(HttpStatusCode.NotFound.GetHashCode(), message.Code);
|
||||||
|
}
|
||||||
|
}
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue