ReC/src/ReC.Application/RecActions/Commands/InvokeRecActionCommand.cs
Developer 02 b78b3e43f4 Add support for custom headers in HTTP requests
Enhanced HTTP request handling by adding support for dynamically including custom headers from the `request.Headers` collection. Implemented a null check to ensure robustness and prevent null reference exceptions when processing headers. This change improves flexibility and customization of HTTP requests.
2025-12-01 09:45:41 +01:00

68 lines
2.4 KiB
C#

using MediatR;
using Microsoft.Extensions.Logging;
using ReC.Application.Common;
using ReC.Application.Common.Dto;
namespace ReC.Application.RecActions.Commands;
public record InvokeRecActionCommand : RecActionDto, IRequest
{
public InvokeRecActionCommand(RecActionDto root) : base(root) { }
public InvokeRecActionCommand() { }
}
public static class InvokeRecActionCommandExtensions
{
public static InvokeRecActionCommand ToInvokeCommand(this RecActionDto dto) => new(dto);
}
public class InvokeRecActionCommandHandler(
IHttpClientFactory clientFactory,
ILogger<InvokeRecActionsCommandHandler>? logger = null
) : IRequestHandler<InvokeRecActionCommand>
{
public async Task Handle(InvokeRecActionCommand request, CancellationToken cancel)
{
using var http = clientFactory.CreateClient();
if (request.RestType is null)
{
logger?.LogWarning(
"Rec action could not be invoked because the RestType value is null. ProfileId: {ProfileId}, ActionId: {ActionId}",
request.ProfileId,
request.ActionId
);
return;
}
using var httpReq = request.RestType
.ToHttpMethod()
.ToHttpRequestMessage(request.EndpointUri);
if(request.Body is not null)
{
using var reqBody = new StringContent(request.Body);
httpReq.Content = reqBody;
}
else if(request.BodyQuery is not null && !request.IsReturnedNoData.BodyQuery)
{
logger?.LogWarning(
"Although BodyQuery returns null, the IsReturnedNoData variable has not been set to TRUE. " +
"This indicates that BodyQueryBehavior has not been executed or that the relevant control step has been skipped. " +
"The relevant behavior must be verified to ensure that the process does not produce unexpected conditions. " +
"ProfileId: {ProfileId}, ActionId: {ActionId}",
request.ProfileId,
request.ActionId
);
}
if (request.Headers is not null)
foreach (var header in request.Headers)
httpReq.Headers.Add(header.Key, header.Value);
using var response = await http.SendAsync(httpReq, cancel);
var body = await response.Content.ReadAsStringAsync(cancel);
var headers = response.Headers.ToDictionary();
}
}