Skip to content

Commit

Permalink
fix: support nullable value type collection in queries
Browse files Browse the repository at this point in the history
  • Loading branch information
TimothyMakkison committed Nov 8, 2024
1 parent 5e7b693 commit b6071c0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
21 changes: 21 additions & 0 deletions Refit.Tests/RestService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,9 @@ public interface IQueryApi

[Get("/foo?{key}={value}")]
Task ParameterMappedQuery(string key, string value);

[Get("/foo")]
Task NullableIntCollectionQuery([Query] int?[] values);
}

public interface IFragmentApi
Expand Down Expand Up @@ -2456,6 +2459,24 @@ public async Task ParameterMappedQueryShouldEscape()
mockHttp.VerifyNoOutstandingExpectation();
}

[Fact]
public async Task NullableIntCollectionQuery()
{
var mockHttp = new MockHttpMessageHandler();
var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, };

mockHttp
.Expect(HttpMethod.Get, "https://github.com/foo")
.WithExactQueryString("values=3%2C4%2C")
.Respond(HttpStatusCode.OK);

var fixture = RestService.For<IQueryApi>("https://github.com", settings);

await fixture.NullableIntCollectionQuery([3, 4, null]);

mockHttp.VerifyNoOutstandingExpectation();
}

[Fact]
public async Task ShouldStripFragment()
{
Expand Down
13 changes: 8 additions & 5 deletions Refit/RequestBuilderImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1349,12 +1349,15 @@ static bool DoNotConvertToQueryMap(object? value)
type = intType.GetGenericArguments()[0];
return ShouldReturn(type);

// Check if type is a simple string or IFormattable type, check underlying type if Nullable<T>
static bool ShouldReturn(Type type) =>
type == typeof(string)
|| type == typeof(bool)
|| type == typeof(char)
|| typeof(IFormattable).IsAssignableFrom(type)
|| type == typeof(Uri);
Nullable.GetUnderlyingType(type) is { } underlyingType
? ShouldReturn(underlyingType)
: type == typeof(string)
|| type == typeof(bool)
|| type == typeof(char)
|| typeof(IFormattable).IsAssignableFrom(type)
|| type == typeof(Uri);
}

static void SetHeader(HttpRequestMessage request, string name, string? value)
Expand Down

0 comments on commit b6071c0

Please sign in to comment.