Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for HTTP body binding #1712

Merged
merged 3 commits into from
Jul 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion extensions/Worker.Extensions.Http/release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@

### Microsoft.Azure.Functions.Worker.Extensions.Http <version>

- <entry>
- Added ability to bind a POCO parameter to the request body using `FromBodyAttribute`
- Special thanks to @njqdev for the contributions and collaboration on this feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker.Extensions.Http.Converters;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Microsoft.Azure.Functions.Worker.Extensions.Http
{
internal class DefaultFromBodyConversionFeature : IFromBodyConversionFeature
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
{
public static IFromBodyConversionFeature Instance { get; } = new DefaultFromBodyConversionFeature();
fabiocav marked this conversation as resolved.
Show resolved Hide resolved

public ValueTask<object?> ConvertAsync(FunctionContext context, Type targetType)
{
var requestDataResult = context.GetHttpRequestDataAsync();

if (requestDataResult.IsCompletedSuccessfully)
{
return ConvertRequestAsync(requestDataResult.Result, context, targetType);
}

return ConvertAsync(requestDataResult, context, targetType);
}

private async ValueTask<object?> ConvertAsync(ValueTask<HttpRequestData?> requestDataResult, FunctionContext context, Type targetType)
{
var requestData = await requestDataResult;
return await ConvertRequestAsync(requestData, context, targetType);
}

private ValueTask<object?> ConvertRequestAsync(HttpRequestData? requestData, FunctionContext context, Type targetType)
{
if (requestData is null)
{
throw new InvalidOperationException($"The '{nameof(DefaultFromBodyConversionFeature)} expects an '{nameof(HttpRequestData)}' instance in the current context.");
}

return ConvertBodyAsync(requestData, context, targetType);
}

private static ValueTask<object?> ConvertBodyAsync(HttpRequestData requestData, FunctionContext context, Type targetType)
{
object? result;

if (targetType == typeof(string))
{
result = requestData.ReadAsString();
}
else if (targetType == typeof(byte[]))
{
result = ReadBytes(requestData, context.CancellationToken);
}
else if (targetType == typeof(Memory<byte>))
{
Memory<byte> bytes = ReadBytes(requestData, context.CancellationToken);
result = bytes;
}
else if (HasJsonContentType(requestData))
{
ObjectSerializer serializer = requestData.FunctionContext.InstanceServices.GetService<IOptions<WorkerOptions>>()?.Value?.Serializer
?? throw new InvalidOperationException("A serializer is not configured for the worker.");

result = serializer.Deserialize(requestData.Body, targetType, context.CancellationToken);
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
throw new InvalidOperationException($"The type '{targetType}' is not supported by the '{nameof(DefaultFromBodyConversionFeature)}'.");
}

return new ValueTask<object?>(result);
}

private static byte[] ReadBytes(HttpRequestData requestData, CancellationToken cancellationToken)
{
var bytes = new byte[requestData.Body.Length];
requestData.Body.Read(bytes, 0, bytes.Length);

return bytes;
}

private static bool HasJsonContentType(HttpRequestData request)
{
var (key, value) = request.Headers
.FirstOrDefault(h => string.Equals(h.Key, "Content-Type", StringComparison.OrdinalIgnoreCase));

if (value is not null
&& MediaTypeHeaderValue.TryParse(value.FirstOrDefault(), out var mediaType)
&& mediaType.MediaType != null)
{

// If the content type is application/json or +json (e.g., application/dl+json)
if (string.Equals(mediaType.MediaType, "application/json", StringComparison.OrdinalIgnoreCase)
|| mediaType.MediaType.EndsWith("+json", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}

return false;
}
}
}
22 changes: 22 additions & 0 deletions extensions/Worker.Extensions.Http/src/FromBodyAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Azure.Functions.Worker.Converters;
using Microsoft.Azure.Functions.Worker.Extensions.Http.Converters;

namespace Microsoft.Azure.Functions.Worker.Http
{
/// <summary>
/// Specifies that a parameter should be bound using the request body.
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
public class FromBodyAttribute : InputConverterAttribute
{
/// <summary>
/// Creates an instance of the <see cref="FromBodyAttribute"/>.
/// </summary>
public FromBodyAttribute()
: base(typeof(FromBodyConverter))
{
}
}
}
34 changes: 34 additions & 0 deletions extensions/Worker.Extensions.Http/src/FromBodyConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker.Converters;

namespace Microsoft.Azure.Functions.Worker.Extensions.Http.Converters
{
internal class FromBodyConverter : IInputConverter
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
{
public ValueTask<ConversionResult> ConvertAsync(ConverterContext context)
{
var bodyConversionFeature = context.FunctionContext.Features.Get<IFromBodyConversionFeature>()
?? DefaultFromBodyConversionFeature.Instance;
fabiocav marked this conversation as resolved.
Show resolved Hide resolved

ValueTask<object?> result = bodyConversionFeature.ConvertAsync(context.FunctionContext, context.TargetType);

if (result.IsCompletedSuccessfully)
{
return new ValueTask<ConversionResult>(ConversionResult.Success(result.Result));
}

return HandleResultAsync(result);
}

private async ValueTask<ConversionResult> HandleResultAsync(ValueTask<object?> result)
{
object? bodyResult = await result;

return ConversionResult.Success(bodyResult);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;

namespace Microsoft.Azure.Functions.Worker.Extensions.Http.Converters
{
/// <summary>
/// Defines an interface for model binding conversion used when binding to
/// the body of an HTTP request.
/// </summary>
public interface IFromBodyConversionFeature
{
/// <summary>
/// Converts the body of an HTTP request to the specified type.
/// </summary>
/// <param name="context">The <see cref="FunctionContext"/> for the invocation.</param>
/// <param name="targetType">The target type for the conversion.</param>
/// <returns>A <see cref="ValueTask{TResult}"/> that completes when the converson is finished.</returns>
fabiocav marked this conversation as resolved.
Show resolved Hide resolved
ValueTask<object?> ConvertAsync(FunctionContext context, Type targetType);
}
}
16 changes: 16 additions & 0 deletions extensions/Worker.Extensions.Http/src/KeyValuePairExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.Collections.Generic;

namespace Microsoft.Azure.Functions.Worker.Extensions.Http
{
internal static class KeyValuePairExtensions
{
internal static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value)
{
key = kvp.Key;
value = kvp.Value;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
<Description>HTTP extensions for .NET isolated functions</Description>

<!--Version information-->
<VersionPrefix>3.0.13</VersionPrefix>
<VersionPrefix>3.1.0</VersionPrefix>
</PropertyGroup>

<Import Project="..\..\..\build\Extensions.props" />

<ItemGroup>
<ProjectReference Include="..\..\Worker.Extensions.Abstractions\src\Worker.Extensions.Abstractions.csproj" />
<ProjectReference Include="..\..\..\src\DotNetWorker.Core\DotNetWorker.Core.csproj" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

### Microsoft.Azure.Functions.Worker.Core <version>

- <entry>
- Unsealed `InputConverterAttribute`. Implementers can now derive from this type to map attributes to custom converters.

### Microsoft.Azure.Functions.Worker.Grpc <version>

Expand Down
9 changes: 8 additions & 1 deletion samples/FunctionApp/HttpTriggerSimple/HttpTriggerSimple.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ namespace FunctionApp
public static class HttpTriggerSimple
{
[Function(nameof(HttpTriggerSimple))]
public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req, FunctionContext executionContext)
public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestData req,
[FromBody] MyPoco myPoco,
FunctionContext executionContext)
{
var sw = new Stopwatch();
sw.Restart();
Expand All @@ -37,4 +39,9 @@ public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "g
return response;
}
}

public class MyPoco
{
public string Name { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace Microsoft.Azure.Functions.Worker.Converters
AttributeTargets.Interface |
AttributeTargets.Enum |
AttributeTargets.Struct)]
public sealed class InputConverterAttribute : Attribute
public class InputConverterAttribute : Attribute
{
/// <summary>
/// Gets the input converter type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@
// Licensed under the MIT License. See License.txt in the project root for license information.

using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker.Tests.OutputBindings;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Xunit;

Expand All @@ -22,7 +19,7 @@ public class HttpRequestDataExtensionsTests
[Fact]
public async Task ReadAsJsonAsync_SimpleOverload_AppliesDefaults()
{
FunctionContext context = CreateContext();
FunctionContext context = TestFunctionContext.Create();

var body = "{\"textjsonname\":\"Test\",\"textjsonint\":42}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(body));
Expand All @@ -38,7 +35,7 @@ public async Task ReadAsJsonAsync_SimpleOverload_AppliesDefaults()
[Fact]
public async Task ReadAsJsonAsync_SerializerOverload_AppliesSerializer()
{
FunctionContext context = CreateContext();
FunctionContext context = TestFunctionContext.Create();

var body = "{\"jsonnetname\":\"Test\",\"jsonnetint\":42}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(body));
Expand All @@ -51,27 +48,6 @@ public async Task ReadAsJsonAsync_SerializerOverload_AppliesSerializer()
Assert.Equal(42, result.SomeInt);
}

private FunctionContext CreateContext(ObjectSerializer serializer = null)
{
var context = new TestFunctionContext();

var services = new ServiceCollection();
services.AddOptions();
services.AddFunctionsWorkerDefaults();

if (serializer != null)
{
services.Configure<WorkerOptions>(c =>
{
c.Serializer = serializer;
});
}

context.InstanceServices = services.BuildServiceProvider();

return context;
}

public class RequestPoco
{
[JsonProperty("jsonnetname")]
Expand Down
28 changes: 28 additions & 0 deletions test/DotNetWorkerTests/TestFunctionContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Serialization;
using Microsoft.Azure.Functions.Worker.Context.Features;
using Microsoft.Azure.Functions.Worker.OutputBindings;
using Microsoft.Azure.Functions.Worker.Tests.Features;
using Microsoft.Extensions.DependencyInjection;

namespace Microsoft.Azure.Functions.Worker.Tests
{
Expand Down Expand Up @@ -101,6 +103,32 @@ public TestFunctionContext(FunctionDefinition functionDefinition, FunctionInvoca

public override CancellationToken CancellationToken => _cancellationToken;

public static TestFunctionContext Create(FunctionDefinition functionDefinition = null,
FunctionInvocation functionInvocation = null, ObjectSerializer serializer = null)
{
functionDefinition ??= new TestFunctionDefinition();
functionInvocation ??= new TestFunctionInvocation();

var context = new TestFunctionContext(functionDefinition, functionInvocation);

var services = new ServiceCollection();
services.AddOptions();
services.AddFunctionsWorkerDefaults();

if (serializer != null)
{
services.Configure<WorkerOptions>(c =>
{
c.Serializer = serializer;
});
}

context.InstanceServices = services.BuildServiceProvider()
.CreateScope().ServiceProvider;

return context;
}

public void Dispose()
{
IsDisposed = true;
Expand Down