-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Description
Describe the bug
If you have service method which calls a controller method and its purpose is to retrieve a single object; however, there is no object which corresponds to the parameters passed in the Url, the GetJsonAsync() method currently returns an error. This seems like a bug as the error message is confusing, the GetJsonAsync() method could handle this condition internally, and the only way to deal with this scenario in your code is to either not use GetJsonAsync() or to wrap the call in an exception handler and catch the error.
To Reproduce
Steps to reproduce the behavior:
- Using version 3.0 of ASP.NET Core
- Run this code: return await http.GetJsonAsync(apiurl + "/" + id);
- Ensure the id does not match a record in your repository
- See error: "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
Expected behavior
The GetJsonAsync() method should not try to deserialize the result if it is an empty string ( "" ). Instead it should return null to the calling application.
Additional context
The current implementation for GetJsonAsync() on Github is:
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
var stringContent = await httpClient.GetStringAsync(requestUri);
return JsonSerializer.Deserialize<T>(stringContent, JsonSerializerOptionsProvider.Options);
}
but it could easily be changed to:
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
var stringContent = await httpClient.GetStringAsync(requestUri);
return (stringContent == "") ? null : JsonSerializer.Deserialize<T>(stringContent, JsonSerializerOptionsProvider.Options);
}
Dealing with the empty string condition would seem to be a more responsible and intuitive solution. And I cannot imagine any negative consequences of this change,