91 lines
2.9 KiB
C#
91 lines
2.9 KiB
C#
using Galaeth.ApiServer.Constants;
|
|
using Galaeth.Core.Constants;
|
|
|
|
namespace Galaeth.ApiServer.Middleware;
|
|
|
|
/// <summary>
|
|
/// Handle status code responses.
|
|
/// </summary>
|
|
public class StatusCodeMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="StatusCodeMiddleware"/> class.
|
|
/// </summary>
|
|
/// <param name="next">Instance of <see cref="RequestDelegate"/>.</param>
|
|
public StatusCodeMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Invoke middleware.
|
|
/// </summary>
|
|
/// <param name="context">Instance of <see cref="HttpContext"/>.</param>
|
|
public Task Invoke(HttpContext context) =>
|
|
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
|
|
{
|
|
Success = false,
|
|
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
|
|
{
|
|
Success = false,
|
|
Error = ApiErrorCodes.UnknownMethod,
|
|
Message = "Unknown method",
|
|
});
|
|
break;
|
|
|
|
case 405:
|
|
context.Response.Headers.Clear();
|
|
context.Response.ContentType = "text/json";
|
|
await context.Response.WriteAsJsonAsync(new
|
|
{
|
|
Success = false,
|
|
Error = ApiErrorCodes.IllegalMethod,
|
|
Message = "Illegal method",
|
|
});
|
|
break;
|
|
|
|
case 415:
|
|
context.Response.Headers.Clear();
|
|
context.Response.ContentType = "text/json";
|
|
await context.Response.WriteAsJsonAsync(new
|
|
{
|
|
Success = false,
|
|
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
|
|
{
|
|
Success = false,
|
|
Error = ApiErrorCodes.UnknownError,
|
|
Message = "Unknown error",
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
}
|