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

Optional header when generating cancellation token in controller results in compilation error #4987

Open
greenmooseSE opened this issue Sep 19, 2024 · 0 comments

Comments

@greenmooseSE
Copy link

Problem Description

Default value for the header parameter is generated both in interface and implementation, while cancellation token only is generated with default value in interface, causing compilation of generated file to fail.

Repro Test

    [Test]
    public void
        GivenOa3ContainsOptionalHeaderAndWeUseCancellationToken_WhenGeneratingControllerCSharpCode_ItResultsInNonCompilableCode()
    {
        var yamlDoc = @"
            openapi: 3.0.0
            info:
              title: Sample API
              version: 1.0.0
            paths:
              /users:
                get:
                  summary: Get all users
                  parameters:
                  - name: X-MyHeader
                    in: header
                    required: false
                    schema:
                      type: string
                  responses:
                    '200':
                      description: A list of users
                      content:
                        application/json:
                          schema:
                            type: array
                            items:
                              type: integer";
        CSharpControllerGeneratorSettings settings = new()
        {
            GenerateOptionalParameters = true, UseCancellationToken = true,
        };
        OpenApiDocument? document = OpenApiYamlDocument.FromYamlAsync(yamlDoc).Result;
        var generator = new CSharpControllerGenerator(document, settings);
        string? code = generator.GenerateFile();
        Console.WriteLine($"Generated code:\n{code}.");

        //The Interface (assert passes)
        code.Should()
            .Contain(
                "string x_MyHeader = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));");
        //The implementation (assert fails) - compile error due to " = null"
        code.Should()
            .NotContain(
                "string x_MyHeader = null, System.Threading.CancellationToken cancellationToken)\n");
    }

Output

Generated code:
//----------------------
// <auto-generated>
//     Generated using the NSwag toolchain v14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------

#pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended."
#pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword."
#pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?'
#pragma warning disable 612 // Disable "CS0612 '...' is obsolete"
#pragma warning disable 649 // Disable "CS0649 Field is never assigned to, and will always have its default value null"
#pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ...
#pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..."
#pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'"
#pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant"
#pragma warning disable 8603 // Disable "CS8603 Possible null reference return"
#pragma warning disable 8604 // Disable "CS8604 Possible null reference argument for parameter"
#pragma warning disable 8625 // Disable "CS8625 Cannot convert null literal to non-nullable reference type"
#pragma warning disable 8765 // Disable "CS8765 Nullability of type of parameter doesn't match overridden member (possibly because of nullability attributes)."

namespace MyNamespace
{
    using System = global::System;

    [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")]
    public interface IController
    {

        /// <summary>
        /// Get all users
        /// </summary>


        /// <returns>A list of users</returns>

        System.Threading.Tasks.Task<System.Collections.Generic.ICollection<int>> UsersAsync(string x_MyHeader = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));

    }

    [System.CodeDom.Compiler.GeneratedCode("NSwag", "14.1.0.0 (NJsonSchema v11.0.2.0 (Newtonsoft.Json v13.0.0.0))")]

    public partial class Controller : Microsoft.AspNetCore.Mvc.ControllerBase
    {
        private IController _implementation;

        public Controller(IController implementation)
        {
            _implementation = implementation;
        }

        /// <summary>
        /// Get all users
        /// </summary>
        /// <returns>A list of users</returns>
        [Microsoft.AspNetCore.Mvc.HttpGet, Microsoft.AspNetCore.Mvc.Route("users")]
        public System.Threading.Tasks.Task<System.Collections.Generic.ICollection<int>> Users([Microsoft.AspNetCore.Mvc.FromHeader(Name = "X-MyHeader")] string x_MyHeader = null, System.Threading.CancellationToken cancellationToken)
        {

            return _implementation.UsersAsync(x_MyHeader, cancellationToken);
        }

    }

    


}

#pragma warning restore  108
#pragma warning restore  114
#pragma warning restore  472
#pragma warning restore  612
#pragma warning restore 1573
#pragma warning restore 1591
#pragma warning restore 8073
#pragma warning restore 3016
#pragma warning restore 8603
#pragma warning restore 8604
#pragma warning restore 8625.
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

No branches or pull requests

1 participant