Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend with overrides from the System.Net.Http.Json assembly #1220

Closed
CarlSjoeholmMyob opened this issue Dec 11, 2024 · 3 comments
Closed

Extend with overrides from the System.Net.Http.Json assembly #1220

CarlSjoeholmMyob opened this issue Dec 11, 2024 · 3 comments
Assignees
Labels
enhancement New feature or request

Comments

@CarlSjoeholmMyob
Copy link

It would be awesome to extend with overrides from the System.Net.Http.Json assembly:

https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions?view=net-8.0

E.g.
[GetFromJsonAsync<TValue>(this HttpClient, String (URL), String (REGIONNAME), String (SERVICENAME), Credentials, CancellationToken)]

Copy link
Contributor

Hi there and welcome to this repository!

A maintainer will be with you shortly, but first and foremost I would like to thank you for taking the time to report this issue. Quality is of the highest priority for us, and we would never release anything with known defects. We aim to do our best but unfortunately you are here because you encountered something we didn't expect. Lets see if we can figure out what went wrong and provide a remedy for it.

@FantasticFiasco
Copy link
Owner

It's clearly valuable, but also taxing from a maintainer perspective as it increases the API surface in a major way. A workaround would be for you to implement the extensions you required and maintain them in your source code, would that be feasible?

@CarlSjoeholmMyob
Copy link
Author

CarlSjoeholmMyob commented Dec 12, 2024

Or we use a simple code in a base class - I'm sure this can be even more prettified :)
Thank you for your answer, and it totally makes sense.

private static JsonSerializerOptions JsonSerializerOptions => new()
{
    UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow
};

private static bool TryDeseralizeJson<TModel>(string json, [NotNullWhen(true)] out TModel? result) where TModel : class
{
    try
    {
        result = JsonSerializer.Deserialize<TModel>(json, JsonSerializerOptions);
        return result is not null;
    }
    catch
    {
        result = default;
        return false;
    }
}

private static HttpContent SerializeJson<TModel>(TModel model, bool overrideContentType) where TModel : class
{
      var jsonContent = new StringContent(JsonSerializer.Serialize(model, JsonSerializerOptions), Encoding.UTF8, "application/json");
      if (overrideContentType)
      {
          // some api's does not like the ;charset=utf-8 addition that is added by default
          jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      }
      return jsonContent;
}

public async Task<UserDto?> GetUserMessageHandler(string userId)
{
    var client = httpClientFactory.CreateClient("");
    var jsonString = await client.GetStringAsync($"/someendpoint/users/{userId}").ConfigureAwait(false);

    return TryDeseralizeJson(jsonString, out UserDto? user)
       ? user
       : throw new InvalidOperationException("Failed to deserialize user data: " + jsonString);
}

public async Task<UserDto> PutUserMessageHandler(UserDto user)
    {
        var client = httpClientFactory.CreateClient("");

        using var jsonContent = SerializeJson(user, true);
        var response = await client.PutAsync($"/someendpoint/user/{user.userId}", jsonContent).ConfigureAwait(false);
        using var content = response.Content;
        var jsonString = await content.ReadAsStringAsync().ConfigureAwait(false);
        return TryDeseralizeJson(jsonString, out UserDto? updatedUser)
            ? updatedUser
            : throw new InvalidOperationException("Failed to deserialize updated user data: " + jsonString);

        throw new InvalidOperationException("Failed to update user data: " + response.ReasonPhrase);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants