Apigateway/ApiGateway/OcelotResponseMiddleware.cs
2022-11-02 11:31:23 -05:00

68 lines
2.2 KiB
C#

using Ocelot.Infrastructure.Extensions;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.Responder;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Caching.Memory;
using Ocelot.Authorization;
using System.Text.RegularExpressions;
namespace ApiGateway
{
public class OcelotResponseMiddleware : Ocelot.Middleware.OcelotMiddleware
{
private readonly RequestDelegate _next;
private readonly IHttpResponder _responder;
private readonly IErrorsToHttpStatusCodeMapper _codeMapper;
public OcelotResponseMiddleware(
RequestDelegate next,
IHttpResponder responder,
IErrorsToHttpStatusCodeMapper codeMapper,
IOcelotLoggerFactory loggerFactory)
: base(loggerFactory.CreateLogger<OcelotResponseMiddleware>())
{
_next = next;
_responder = responder;
_codeMapper = codeMapper;
}
public async Task Invoke(HttpContext httpContext)
{
//var x = CustomLogic.Authorize(httpContext);
await _next.Invoke(httpContext);
if (httpContext.Response.HasStarted)
return;
var errors = httpContext.Items.Errors();
if (errors.Count > 0)
{
Logger.LogWarning($"{errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{httpContext.Request.Path}, request method: {httpContext.Request.Method}");
var statusCode = _codeMapper.Map(errors);
var error = string.Join(",", errors.Select(x => x.Message));
httpContext.Response.StatusCode = statusCode;
// output error
await httpContext.Response.WriteAsync(error);
}
else
{
Logger.LogDebug("no pipeline errors, setting and returning completed response");
var downstreamResponse = httpContext.Items.DownstreamResponse();
await _responder.SetResponseOnHttpContext(httpContext, downstreamResponse);
}
}
}
}