Skip to content

Conversation

EraYaN
Copy link
Contributor

@EraYaN EraYaN commented Oct 2, 2025

Quite some small changes in this PR, felt like a waste to split them up. Commit f814598 could be expanded to include even more versions of .NET if so desired.

8a7edb2 - Update documentation and samples

0bfc7f8 - Support multi targetting
This makes it so that when you have both net8 and net9 (for example) the csproj includes both. This makes sure that consumers of your package will get to use the newest transitive dependencies.

c3b74e5 - Expose ContentHeaders on ApiResponse, to access ContentDisposition for example with file downloads.
Very useful for downloading files, you can now access details and many more headers about the actual Content.

f35af99 - Include full response object in ApiException
This gives adds a lot of convenience to debugging using a generated API client.

c56afb2 - Add support for other Accept header values or full arrays when multiple options are present.
This uses the correct (array) for the Accept header for non json responses.

a98c339 - Make TokenProvider not contain state so subclassing actually works correctly with JIT requested tokens (for long lived ApiClients)
This allows the ApiClient to use say client credentials and an OAuth flow to requests and cache tokens appropriately without knowing the tokens before hand.

Example implementation
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using ApiTest.Shared;
using Calcasa.Api;
using Calcasa.Api.Client;
using Duende.IdentityModel.Client;
using Microsoft.Extensions.Options;

public class ServiceOAuthTokenProvider : TokenProvider<OAuthToken>
{
    private readonly string ClientId;
    private readonly string ClientSecret;
    private readonly string TokenUrl;
    private readonly HttpClient AuthClient;
    private ConcurrentDictionary<string, (TokenResponse Token, DateTime ExpiresOn)> Tokens;

    public ServiceOAuthTokenProvider(IOptions<CalcasaApiOptions> options)
    {
        Tokens = [];
        ClientId = options.Value.ClientId;
        ClientSecret = options.Value.ClientSecret;
        TokenUrl = options.Value.TokenUrl;
        AuthClient = new HttpClient();
    }

    public override ValueTask<OAuthToken> GetAsync(string header = "", CancellationToken cancellation = default)
    {
        var data = Tokens.GetValueOrDefault(header);

        if (data.Token != null)
        {
            if (!data.Token.IsError || data.ExpiresOn > DateTime.UtcNow)
            {
                return ValueTask.FromResult(new OAuthToken(data.Token.AccessToken));
            }
        }

        var request = new ClientCredentialsTokenRequest
        {
            Address = TokenUrl,
            ClientId = ClientId,
            ClientSecret = ClientSecret,
            ClientCredentialStyle = ClientCredentialStyle.AuthorizationHeader, // Recommended as opposed to secrets in body.
        };

        data.Token = AuthClient.RequestClientCredentialsTokenAsync(request).Result;

        if (data.Token.IsError)
        {
            throw new ApplicationException("Could not refresh token: [" + data.Token.ErrorType + "] " + data.Token.Error + "; " + data.Token.ErrorDescription);
        }
        else
        {
            data.ExpiresOn = DateTime.UtcNow.AddSeconds(data.Token.ExpiresIn);
            Tokens.AddOrUpdate(header, (h) => data, (h, oldData) => data);

            return ValueTask.FromResult(new OAuthToken(data.Token.AccessToken));
        }
    }
}

74ab0ef - Fix DateOnly parsing, DateTimeStyles are not supported in TryParseExact
This fixes the calls to TryParseExact so they actually work, the DateTimeStyles besides None are not supported when say parsing the string "2025-07-01" which is absolutely in the given formats array. (It hits this case)

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    (For Windows users, please run the script in WSL)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR solves a reported issue, reference it using GitHub's linking syntax (e.g., having "fixes #123" present in the PR description)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

C# Technical Committee
@mandrean @shibayan @Blackclaws @lucamazzanti @iBicha

@devhl-labs

The generator seems to still support the netstandard1.* targets but none of the dependencies still list those on Nuget. Seems like they are fully abandoned/deprecated.

And has generichost ever supported .NET4.7 and .NET4.8? Seems like System.Text.Json is missing regardless of the changes in this PR.

@EraYaN EraYaN changed the title C# GenericHost udpate to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens Oct 2, 2025
@EraYaN EraYaN changed the title C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting. exposing more headers and proper JIT tokens C# GenericHost changes to facilitate better Accept header support, DateOnly parsing, multitargetting, exposing more headers and proper JIT tokens Oct 2, 2025
@EraYaN EraYaN force-pushed the generichost-updates branch 3 times, most recently from afab356 to fdf530c Compare October 2, 2025 12:50
@EraYaN EraYaN force-pushed the generichost-updates branch from fdf530c to fa75fef Compare October 2, 2025 12:53
@EraYaN EraYaN force-pushed the generichost-updates branch from fa75fef to 8a7edb2 Compare October 2, 2025 12:58
@wing328
Copy link
Member

wing328 commented Oct 6, 2025

thanks for the PR

can you please review the build failure when you've time?

@EraYaN
Copy link
Contributor Author

EraYaN commented Oct 6, 2025

I had forgotten that the nullable reference types are supposed to be in a conditional block. And collection expressions are also unavailable.

@wing328
Copy link
Member

wing328 commented Oct 13, 2025

@devhl-labs does this change look good to you? If yes, we will merge it for the upcoming v7.17.0 release.

@devhl-labs
Copy link
Contributor

devhl-labs commented Oct 13, 2025

Thank you for the PR. I look forward to getting your fixes in. I do ask that you split this into multiple PRs. I know that is a pain and may feel tedious (I went through this as well multiple times when adding generic host, wing will tell you!), but there are good reasons for it:

  1. easier to review
  2. easier to revert when problems are found without reverting working code
  3. easier to see where we are lacking tests

Developers can provide their own token providers, can you explain why you want to change the provider and token? For the project, we probably need changes to that file, it just looks kind of like you've got {{#netStandard}} condition=true AllTheThings {{/netStandard}}

The generator seems to still support the netstandard1.* targets but none of the dependencies still list those on Nuget. Seems like they are fully abandoned/deprecated.

I don't have any samples on netstandard1.* but it is supposed to be supported. Personally I don't have any stake in its support but I think the community might want it. I'm not positive what you're saying is wrong though.

And has generichost ever supported .NET4.7 and .NET4.8? Seems like System.Text.Json is missing regardless of the changes in this PR.

There are samples for both so it should work.

This introduces new build warnings. I took great effort to remove all warnings except the deprecated warnings. Please fix that before merging. Here is an on of the warnings:

Warning: /home/runner/work/openapi-generator/openapi-generator/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Client/ClientUtils.cs(251,24): warning CS8603: Possible null reference return. [/home/runner/work/openapi-generator/openapi-generator/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj]

There is already a pr out for the DateOnly issue. #22099

/// <param name="statusCode"></param>
/// <param name="rawContent"></param>
public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent)
public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent, System.Net.Http.HttpResponseMessage? rawResponse = null) : base(reasonPhrase ?? rawContent)
Copy link
Contributor

@devhl-labs devhl-labs Oct 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we need the string and the HttpResponseMessage? I think the message would contain the string, but betting it is probably an async operation. Perhaps the await on that string should not be in the api, but rather somewhere in the exception's class? Just kind of brainstorming here. Also, doesn't the response inherit IDisposable? Should we let it live?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants