using System.Runtime.CompilerServices;
using Elsa.Workflows;
using Elsa.Workflows.Attributes;
namespace Elsa.Http;
///
/// Send an HTTP request.
///
[Activity("Elsa", "HTTP", "Send an HTTP request.", DisplayName = "HTTP Request", Kind = ActivityKind.Task)]
public class SendHttpRequest : SendHttpRequestBase
{
///
public SendHttpRequest([CallerFilePath] string? source = null, [CallerLineNumber] int? line = null) : base(source, line)
{
}
///
/// A list of expected status codes to handle and the corresponding activity to execute when the status code matches.
///
[Input(
Description = "A list of expected status codes to handle and the corresponding activity to execute when the status code matches.",
UIHint = "http-status-codes"
)]
public ICollection ExpectedStatusCodes { get; set; } = new List();
///
/// The activity to execute when the HTTP status code does not match any of the expected status codes.
///
[Port]
public IActivity? UnmatchedStatusCode { get; set; }
///
/// The activity to execute when the HTTP request fails to connect.
///
[Port]
public IActivity? FailedToConnect { get; set; }
///
/// The activity to execute when the HTTP request times out.
///
[Port]
public IActivity? Timeout { get; set; }
///
protected override async ValueTask HandleResponseAsync(ActivityExecutionContext context, HttpResponseMessage response)
{
var expectedStatusCodes = ExpectedStatusCodes;
var statusCode = (int)response.StatusCode;
var matchingCase = expectedStatusCodes.FirstOrDefault(x => x.StatusCode == statusCode);
var activity = matchingCase != null ? matchingCase.Activity : UnmatchedStatusCode;
await context.ScheduleActivityAsync(activity, OnChildActivityCompletedAsync);
}
///
protected override async ValueTask HandleRequestExceptionAsync(ActivityExecutionContext context, HttpRequestException exception)
{
await context.ScheduleActivityAsync(FailedToConnect, OnChildActivityCompletedAsync);
}
///
protected override async ValueTask HandleTaskCanceledExceptionAsync(ActivityExecutionContext context, TaskCanceledException exception)
{
await context.ScheduleActivityAsync(Timeout, OnChildActivityCompletedAsync);
}
private async ValueTask OnChildActivityCompletedAsync(ActivityCompletedContext context)
{
await context.TargetContext.CompleteActivityAsync();
}
}