// // Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License. // using Astral.ApiServer.Core; using Astral.ApiServer.Models.Common; using Astral.Core.Constants; namespace Astral.ApiServer.Middleware; /// /// Handle status code responses. /// public class StatusCodeMiddleware { private readonly RequestDelegate _next; /// /// Initializes a new instance of the class. /// /// Instance of . public StatusCodeMiddleware(RequestDelegate next) { _next = next; } /// /// Invoke middleware. /// /// Instance of . public Task Invoke(HttpContext context) { return InvokeAsync(context); } private async Task InvokeAsync(HttpContext context) { await _next(context); switch (context.Response.StatusCode) { case 401: context.Response.Headers.Clear(); context.Response.ContentType = "text/json"; await context.Response.WriteAsJsonAsync(new ErrorResultModel { Error = CoreErrorCodes.Unauthorized, Message = "You're not authorized to do that" }); break; case 404: context.Response.Headers.Clear(); context.Response.ContentType = "text/json"; await context.Response.WriteAsJsonAsync(new ErrorResultModel { Error = ApiErrorCodes.UnknownMethod, Message = "Unknown method" }); break; case 405: context.Response.Headers.Clear(); context.Response.ContentType = "text/json"; await context.Response.WriteAsJsonAsync(new ErrorResultModel { Error = ApiErrorCodes.IllegalMethod, Message = "Illegal method" }); break; case 415: context.Response.Headers.Clear(); context.Response.ContentType = "text/json"; await context.Response.WriteAsJsonAsync(new ErrorResultModel { Error = ApiErrorCodes.UnsupportedBody, Message = "Unsupported body/media type" }); break; case 500: context.Response.Headers.Clear(); context.Response.ContentType = "text/json"; await context.Response.WriteAsJsonAsync(new ErrorResultModel { Error = ApiErrorCodes.UnknownError, Message = "Unknown error" }); break; } } }