Added more security and metrics
This commit is contained in:
+21
-13
@@ -1,6 +1,6 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using EonaCat.Json;
|
||||
|
||||
namespace EonaCat.DoxaApi.Middleware
|
||||
{
|
||||
@@ -32,12 +32,20 @@ namespace EonaCat.DoxaApi.Middleware
|
||||
"host", "content-length", "connection", "transfer-encoding"
|
||||
};
|
||||
|
||||
public static async Task HandleAsync(HttpContext context, JsonSerializerOptions writeOptions)
|
||||
private static readonly JsonSerializerSettings _settings = new()
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
Formatting = Formatting.Indented
|
||||
};
|
||||
|
||||
public static async Task HandleAsync(HttpContext context, JsonSerializerSettings writeOptions)
|
||||
{
|
||||
ConsoleRequest? req;
|
||||
try
|
||||
{
|
||||
req = await JsonSerializer.DeserializeAsync<ConsoleRequest>(context.Request.Body, ReadOptions);
|
||||
using var reader = new StreamReader(context.Request.Body);
|
||||
var json = await reader.ReadToEndAsync();
|
||||
req = JsonHelper.ToObject<ConsoleRequest>(json);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -116,35 +124,35 @@ namespace EonaCat.DoxaApi.Middleware
|
||||
};
|
||||
|
||||
context.Response.ContentType = "application/json; charset=utf-8";
|
||||
await JsonSerializer.SerializeAsync(context.Response.Body, result, writeOptions);
|
||||
var json = JsonHelper.ToJson(result, writeOptions);
|
||||
await context.Response.WriteAsync(json, Encoding.UTF8);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
context.Response.StatusCode = 504;
|
||||
await JsonSerializer.SerializeAsync(context.Response.Body, new ConsoleResponse
|
||||
var errorResponse = new ConsoleResponse
|
||||
{
|
||||
StatusCode = 0,
|
||||
ElapsedMs = sw.ElapsedMilliseconds,
|
||||
NetworkError = true,
|
||||
Body = "Request timed out after 30 seconds."
|
||||
}, writeOptions);
|
||||
};
|
||||
var json = JsonHelper.ToJson(errorResponse, writeOptions);
|
||||
await context.Response.WriteAsync(json, Encoding.UTF8);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
context.Response.StatusCode = 502;
|
||||
await JsonSerializer.SerializeAsync(context.Response.Body, new ConsoleResponse
|
||||
var errorResponse = new ConsoleResponse
|
||||
{
|
||||
StatusCode = 0,
|
||||
ElapsedMs = sw.ElapsedMilliseconds,
|
||||
NetworkError = true,
|
||||
Body = ex.Message
|
||||
}, writeOptions);
|
||||
};
|
||||
var json = JsonHelper.ToJson(errorResponse, writeOptions);
|
||||
await context.Response.WriteAsync(json, Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions ReadOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user