Skip to content

Commit

Permalink
Fix condition of method return type in RequestBuilder to only allow T…
Browse files Browse the repository at this point in the history
…ask<> and IObservable<> (#1364)

* Fix condition of generic return type in method info

* add test

* Update RestMethodInfo.cs

---------

Co-authored-by: barle <[email protected]>
Co-authored-by: Glenn <[email protected]>
  • Loading branch information
3 people authored Apr 13, 2023
1 parent 857becc commit c8888e1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
11 changes: 11 additions & 0 deletions Refit.Tests/RequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@ public interface IRestMethodInfoTests

[Get("/api/{id}")]
Task IEnumerableThrowingError([Query(CollectionFormat.Multi)] IEnumerable<string> values);

[Get("/foo")]
List<string> InvalidGenericReturnType();
}

public enum TestEnum { A, B, C }
Expand Down Expand Up @@ -1146,6 +1149,14 @@ public void ParameterMappingWithHeaderQueryParamAndQueryArrayParam()
Assert.Single(fixture.HeaderParameterMap);
Assert.Single(fixture.PropertyParameterMap);
}

[Fact]
public void GenericReturnTypeIsNotTaskOrObservableShouldThrow()
{
var input = typeof(IRestMethodInfoTests);
Assert.Throws<ArgumentException>(() => new RestMethodInfo(input,
input.GetMethods().First(x => x.Name == nameof(IRestMethodInfoTests.InvalidGenericReturnType))));
}
}

[Headers("User-Agent: RefitTestClient", "Api-Version: 1")]
Expand Down
7 changes: 4 additions & 3 deletions Refit/RestMethodInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -463,8 +463,9 @@ static Dictionary<int, string> BuildHeaderParameterMap(List<ParameterInfo> param
void DetermineReturnTypeInfo(MethodInfo methodInfo)
{
var returnType = methodInfo.ReturnType;
if (returnType.IsGenericType && (methodInfo.ReturnType.GetGenericTypeDefinition() != typeof(Task<>)
|| methodInfo.ReturnType.GetGenericTypeDefinition() != typeof(IObservable<>)))
if (returnType.IsGenericType && (methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)
|| methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(ValueTask<>)
|| methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(IObservable<>)))
{
ReturnType = returnType;
ReturnResultType = returnType.GetGenericArguments()[0];
Expand All @@ -488,7 +489,7 @@ void DetermineReturnTypeInfo(MethodInfo methodInfo)
DeserializedResultType = typeof(void);
}
else
throw new ArgumentException($"Method \"{methodInfo.Name}\" is invalid. All REST Methods must return either Task<T> or IObservable<T>");
throw new ArgumentException($"Method \"{methodInfo.Name}\" is invalid. All REST Methods must return either Task<T> or ValueTask<T> or IObservable<T>");
}

void DetermineIfResponseMustBeDisposed()
Expand Down

0 comments on commit c8888e1

Please sign in to comment.