Skip to content

HttpClient.GetFromJsonAsync<T> does not handle 204 returned by ASP.NET Core #113941

Open
@dashiell-zhang

Description

@dashiell-zhang

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

dotnet/aspnetcore#43608

This question has been closed, but the problem itself has not been solved. When the remote interface returns 204, because there is no information in the content, calling this method will directly trigger an exception. I personally think that a more reasonable solution here is to return null instead of throwing an exception directly.

At present, I have to wrap it myself, but I feel that this is a very strange behavior

        public static async Task<TValue?> GetFromJsonAsync<TValue>(this HttpClient client, string requestUri)
        {
            var response = await client.GetAsync(requestUri);
            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return default;
            }
            return await response.Content.ReadFromJsonAsync<TValue>(jsonToObjectOptions);
        }

Expected Behavior

When the status code is 204 or the Content is empty, Null is returned directly instead of an exception.

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

9.0.201

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions