Skip to content

Commit

Permalink
Fixed handling requests without a Content-Type header, and writing de…
Browse files Browse the repository at this point in the history
…fault values in responses.
  • Loading branch information
jezzsantos committed Oct 28, 2024
1 parent 81f78c5 commit 5f20ea5
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
19 changes: 16 additions & 3 deletions src/Infrastructure.Web.Api.Common.UnitTests/WebRequestSpec.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using System.Text.Json;
using FluentAssertions;
using Infrastructure.Web.Api.Interfaces;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Primitives;
using Moq;
using Xunit;

namespace Infrastructure.Web.Api.Common.UnitTests;
Expand All @@ -14,6 +16,14 @@ public class WebRequestSpec
[Trait("Category", "Unit")]
public class GivenAJsonRequest
{
private readonly Mock<IServiceProvider> _serviceProvider;

public GivenAJsonRequest()
{
_serviceProvider = new Mock<IServiceProvider>();
_serviceProvider.Setup(sp => sp.GetService(typeof(JsonSerializerOptions)))
.Returns(JsonSerializerOptions.Default);
}
[Fact]
public async Task WhenBindAsyncAndEmptyHttpRequest_ThenReturnsInstance()
{
Expand All @@ -23,7 +33,8 @@ public async Task WhenBindAsyncAndEmptyHttpRequest_ThenReturnsInstance()
{
ContentType = HttpConstants.ContentTypes.Json,
Body = new MemoryStream("{}"u8.ToArray())
}
},
RequestServices = _serviceProvider.Object
};

var result = await TestRequest.BindAsync(context, null!);
Expand All @@ -49,7 +60,8 @@ public async Task WhenBindAsyncAndPropertiesInQueryString_ThenReturnsInstance()
{ nameof(TestRequest.ANumberProperty), "999" },
{ nameof(TestRequest.AStringProperty), "avalue" }
})
}
},
RequestServices = _serviceProvider.Object
};

var result = await TestRequest.BindAsync(context, null!);
Expand All @@ -75,7 +87,8 @@ public async Task WhenBindAsyncAndPropertiesInRouteValues_ThenReturnsInstance()
{ nameof(TestRequest.ANumberProperty), "999" },
{ nameof(TestRequest.AStringProperty), "avalue" }
}
}
},
RequestServices = _serviceProvider.Object
};

var result = await TestRequest.BindAsync(context, null!);
Expand Down
20 changes: 19 additions & 1 deletion src/Infrastructure.Web.Api.Interfaces/WebRequests.AspNet.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.ComponentModel;
using System.Reflection;
using System.Text.Json;
using Common.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Infrastructure.Web.Api.Interfaces;

Expand All @@ -26,13 +28,29 @@ public abstract partial class WebRequest<TRequest>
}
else
{
var requestDto = await request.ReadFromJsonAsync<TRequest>();
var requestDto = await CreateFromJson(context);
PopulateFromQueryStringValues(request, requestDto);
PopulateFromRouteValues(request, requestDto);
return requestDto;
}
}

/// <summary>
/// Returns the request DTO, populated from the JSON of the request, or an empty instance if the request has no JSON
/// content
/// </summary>
private static async Task<TRequest?> CreateFromJson(HttpContext context)
{
var jsonOptions = context.RequestServices.GetRequiredService<JsonSerializerOptions>();
var request = context.Request;
if (request.HasJsonContentType())
{
return await request.ReadFromJsonAsync<TRequest>(jsonOptions);
}

return JsonSerializer.Deserialize<TRequest>("{}", jsonOptions);
}

/// <summary>
/// Populate properties of the specified <see cref="requestDto" /> from any form values
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ void RegisterWireFormats()
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
serializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, false));
serializerOptions.Converters.Add(new JsonDateTimeConverter(DateFormat.Iso8601));
Expand Down

0 comments on commit 5f20ea5

Please sign in to comment.