Improve automatic handling of content parsing and writing

This commit is contained in:
Sipke Schoorstra 2023-03-09 11:24:00 +01:00
parent ba02b80fb0
commit d85e8a6c5e
2 changed files with 9 additions and 4 deletions

View file

@ -1,5 +1,6 @@
using System.Net;
using System.Net.Mime;
using System.Text.Json.Nodes;
using Elsa.Extensions;
using Elsa.Http.ContentWriters;
using Elsa.Http.Models;
@ -94,7 +95,7 @@ public class WriteHttpResponse : CodeActivity
if (content == null)
return;
var contentType = ContentType.TryGet(context) ?? MediaTypeNames.Text.Plain;
var contentType = ContentType.TryGet(context);
if (string.IsNullOrWhiteSpace(contentType))
contentType = DetermineContentType(content);
@ -109,5 +110,9 @@ public class WriteHttpResponse : CodeActivity
await httpContent.CopyToAsync(response.Body);
}
private string DetermineContentType(object? content) => content is byte[] or Stream ? "application/octet-stream" : "text/plain";
private string DetermineContentType(object? content) => content is byte[] or Stream
? "application/octet-stream"
: content is string
? "text/plain"
: "application/json";
}

View file

@ -21,11 +21,11 @@ public class TextContentFactory : IHttpContentFactory
/// <inheritdoc />
public HttpContent CreateHttpContent(object content, string contentType)
{
var text = content as string ?? "";
var text = content as string ?? content.ToString();
if (string.IsNullOrWhiteSpace(contentType))
contentType = MediaTypeNames.Text.Plain;
return new StringContent(text, Encoding.UTF8, contentType);
return new StringContent(text!, Encoding.UTF8, contentType);
}
}