elsa-workflows / elsa-core

A .NET workflows library
https://v3.elsaworkflows.io/
MIT License
6.49k stars 1.2k forks source link

[BUG] Http Request activity and application/x-www-form-urlencoded #5888

Closed pvdbk closed 2 weeks ago

pvdbk commented 3 months ago

Description

the class FormUrlEncodedHttpContentFactory does not work to build a HttpContent from standard types

Steps to Reproduce

In the activity "HTTP Request (flow)", use "application/x-www-form-urlencoded" as "Content Type" and an object (built with the JAVASCRIPT way) or a string as "Content".

image

Launching the resulting workflow, you get this error when "Content" is an object.

image

Or this one if "Content" is a string

image

pvdbk commented 3 months ago

Here is the code of the class in question

using System.Text.Json;
using System.Text.Json.Nodes;

namespace Elsa.Http.ContentWriters;

/// <summary>
/// A content writer that writes content in the application/x-www-form-urlencoded format. 
/// </summary>
public class FormUrlEncodedHttpContentFactory : IHttpContentFactory
{
    /// <inheritdoc />
    public IEnumerable<string> SupportedContentTypes => new[] { "application/x-www-form-urlencoded" };

    /// <inheritdoc />
    public HttpContent CreateHttpContent(object content, string? contentType = null) => new FormUrlEncodedContent(GetContentAsDictionary(content));

    private static Dictionary<string, string> GetContentAsDictionary(object content) =>
        (content is string or JsonObject
            ? JsonSerializer.Deserialize<Dictionary<string, string>>(JsonSerializer.Serialize(content))
            : (Dictionary<string, string>)Convert.ChangeType(content, typeof(Dictionary<string, string>)))!;
}

When content is a string, it can not work : The string is serialized then deserialized as a dictionary, but the serialized result can only be deserialized as a string.

When content is an ExpandoObject, it can not work either : Convert.ChangeType does not accept this type.

The JsonObject type is well handled, but does not seem to be an usual activity output type.

sfmskywalker commented 2 weeks ago

@pvdbk thanks for the detailed bug report! This has now been fixed via https://github.com/elsa-workflows/elsa-core/pull/6074