Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Apr 21 19:29
    dependabot[bot] labeled #3433
  • Apr 21 19:29
    dependabot[bot] labeled #3433
  • Apr 21 19:29
    dependabot[bot] opened #3433
  • Apr 21 19:29

    dependabot[bot] on nuget

    Bump System.Net.Http from 4.3.2… (compare)

  • Apr 21 19:29
    dependabot[bot] labeled #3432
  • Apr 21 19:29
    dependabot[bot] labeled #3432
  • Apr 21 19:29
    dependabot[bot] opened #3432
  • Apr 21 19:29

    dependabot[bot] on nuget

    Bump System.Net.Http in /src/NS… (compare)

  • Apr 21 19:29
    dependabot[bot] labeled #3431
  • Apr 21 19:29
    dependabot[bot] labeled #3431
  • Apr 21 19:29
    dependabot[bot] opened #3431
  • Apr 21 19:29

    dependabot[bot] on nuget

    Bump System.Net.Http in /src/NS… (compare)

  • Apr 21 19:16
    dependabot[bot] labeled #3430
  • Apr 21 19:16
    dependabot[bot] labeled #3430
  • Apr 21 19:16
    dependabot[bot] opened #3430
  • Apr 21 19:16
    dependabot[bot] labeled #3429
  • Apr 21 19:16
    dependabot[bot] labeled #3429
  • Apr 21 19:16

    dependabot[bot] on nuget

    Bump System.Net.Http from 4.3.2… (compare)

  • Apr 21 19:16

    dependabot[bot] on nuget

    Bump System.Net.Http from 4.3.2… (compare)

  • Apr 21 19:16
    dependabot[bot] opened #3429
Hobbes Pirakitti
@hobbes-visionfriendly-com

@RicoSuter - I am able to reproduce my "home route" problem starting from the sample "SampleOwinWebApiWithSwaggerUi" found here: https://github.com/NSwag/Samples/tree/master/src . Steps: 1) Run the sample and confirm that the home page shows up. 2) Upgrade all NSwag NuGet packages to 13.9.4. 3) In Startup.cs, change the call "UseSwaggerUi" to

UseSwaggerUi3(typeof(Startup).Assembly, s =>
{
s.Path = "/foo";
s.SwaggerRoutes.Add(new SwaggerUi3Route("My Fancy API v1", "/qwerty/asdf.json"));
});

Now when you run the project, instead of the home page, you see that it has been "hijacked" by raw Swagger JSON.

Hobbes Pirakitti
@hobbes-visionfriendly-com
Ah, I found the solution: RicoSuter/NSwag#1797
cjb110
@cjb110

I've being using the partial client to add my JWT bearer tokens, but for some reason they don't always get added. But I can't see why.

async partial void PrepareRequest(HttpClient client, HttpRequestMessage request, string url)
        {
            _logger.LogInformation($"Prepare Request: {request.RequestUri.AbsoluteUri}");
            var user = await _storage.GetItem<LoginResult>("user");

            if (user != null)
            {
                _logger.LogInformation($"Adding Auth Header: {user.UserName}, {user.JwtToken}");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", user.JwtToken);
            }
        }

I can see in the chrome log the 'Preparing Request' and 'Adding Auth Header' messages, but the request has none added...its like the client as fired off the request already?

cjb110
@cjb110
just changed in to request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.JwtToken); but no luck there either. Going to see if its the aysnc/awaits...
cjb110
@cjb110
Yep, it was the asynchronous part, as the client doesn't await PrepareRequest, the request is sent before the headers are added. So to fix I used the Blazord.LocalStorage package which has synchronous versions of Get/Set item.
Rico Suter
@RicoSuter
async void is almost always evil ..
cjb110
@cjb110
On the consumer side of the NSwag client, how can tell it not to pass some fields back? I've had to add some DateTime fields as the Blazor UI toolkit I'm using doesn't support the DateTimeOffset type, but these fields are being passed back to the API. I've tried JsonIgnore, doesn't seem to change things.
ooo, just noticed that the client uses the Newtonsoft Json to serialize, I think most of the rest of my client is the .net json lib.
cjb110
@cjb110
Yep that was it, need the different using statement...but meh wasn't the actual cause of my bug...
cjb110
@cjb110
Ok next issue:) The API is returning ProblemDetails, and I can see that in the actual response. I can see the generated client throws an ApiException<ProblemDetails>, how do I get to my detail message when I'm catching it?
Rico Suter
@RicoSuter
e.Result?
cjb110
@cjb110
it was, but only after i changed the catch to catch(ApiException<ProblemDetails> ex), never seen generics in exceptions before so didn't think to do that bit!
kelly
@kellyprankin
I am trying to send a File as part of a form from the front end to the backend
I added an IFormFile to my back end model and then I used TypeScript generation, but the property seemed to come out as a string instead of anything to do with a File
kelly
@kellyprankin
OK, so it looks like it works OK if you make it a separate parameter, but it will not work if it is a property on a regular class file
kelly
@kellyprankin
Guess I'll post an issue and see if anyone knows whats up
Coops9
@Coops9

Hi. I am using Nswag and generating typescript API definition from an api that has the attribute [OpenApiBodyParameter("application/octet-stream")]
//[ValidateAntiForgeryToken]
public async Task<ActionResult> Upload()

However the generated api code specifies Blob instead of File

upload(body: Blob | null | undefined): Promise<FileResponse | null> {

which generates an error when trying to read the content-type boundary. is there any other attribute I should be using so it generates the api with File instead of Blob?
related: RicoSuter/NSwag#2493

Tiago Ribeiro
@TrymBeast_twitter
Hey! What is the best way to describe a resource that is always application/zip? I have tried using the Produces attribute, but that seems to be used in conjunction with content negotiation, and I don't care about content negotiation in this resource, it will always be a zip file no matter what.
Tiago Ribeiro
@TrymBeast_twitter
Also in an IOperationProcessor I'm trying to get the response type, but I'm having some trouble finding it. Does anyone know how to get it?
Rico Suter
@RicoSuter
@Coops9 [OpenApiBodyParameter] is really the whole body and not form-data, for that i think you need to use the regular asp.net core form data constructs to get the correct openapi
@TrymBeast_twitter i think you need to use Produces which is however only picket up with correct content registrations (see asp) with the processor you should be able to change/update the response in context.Operation.Responses (or similar), no?
James Catterall
@JCattera
Hi, I'm generating C# client code for my API from an OpenAPI 3.0 yaml file, but the line that corresponds to adding a json part of a multipart/form-data request doesn't set the media type of the StringContent as "application/json". Is this currently unsupported by the code generator?
the generated code is content_.Add(new System.Net.Http.StringContent(ConvertToString(profile, System.Globalization.CultureInfo.InvariantCulture)), "profile");
but it should be content_.Add(new System.Net.Http.StringContent(ConvertToString(profile, System.Globalization.CultureInfo.InvariantCulture), System.Text.Encoding.UTF8, "application/json"), "profile");
Jérémy VIGNELLES
@jeremyVignelles
feel free to open a PR, I guess

as per the spec: https://swagger.io/specification/#special-considerations-for-multipart-content

If the property is complex, or an array of complex values, the default Content-Type is application/json

Tiago Ribeiro
@TrymBeast_twitter
@RicoSuter With a processor I can override the content type, but I was just wondering if there was some way out of the box to do it. Thanks!
Jérémy VIGNELLES
@jeremyVignelles
@TrymBeast_twitter are you looking for [Produces("your/content-type")]?
Ghimpu Lucian Eduard
@GhimpuLucianEduard
Hello guys, quick question. Is it possible to specify the known types and JSON converter without using the attributes (https://github.com/RicoSuter/NJsonSchema/wiki/Inheritance) ? As far as I can see in the code, for the actual schema to be generated, it will look up for those attributes, right?
Rico Suter
@RicoSuter
You can implement your own generic converter inheriting from the one in NJS and add a static property: Same as for the new STJ converter I'm working on:
https://github.com/RicoSuter/NJsonSchema/pull/1308/files#diff-d7f1890f854771a283e5941025ae588613335e2194b8a77711a78efa16215a67R17
Ghimpu Lucian Eduard
@GhimpuLucianEduard
@RicoSuter I'm not that familiar with the entire codebase, but how would this work with NSwag and the generation of oneOf in the OpenApi schemas. My end goal is that, to have an open API document generated and then typescript services with all the inheritance (using oneOf and mapping the discriminator) BUT without using attributes?
Or is some part of the api specification generated based on the json converters? I'm looking here https://github.com/RicoSuter/NJsonSchema/blob/0f71480bdbd67c1ab2ae5584f8377a3cdd823e6b/src/NJsonSchema/Generation/JsonSchemaGenerator.cs by the way, but again I'm not that familiar with the code, maybe I'm missing something
Ghimpu Lucian Eduard
@GhimpuLucianEduard
image.png
Sorry not oneOf but allOf:
Rico Suter
@RicoSuter
yes, inheritance is generated based on this converter, and if you dont want to specify knowntypeattributes you can override it and provide it differently in the converter
Ghimpu Lucian Eduard
@GhimpuLucianEduard
[Route("api/[controller]")]
[ApiController]
public class FruitController : ControllerBase
{
    [HttpGet]
    [Route("all")]
    public ActionResult<IEnumerable<Fruit>> GetAll()
    {
        return Ok(new List<Fruit>(){
            new Apple { Type = "apple", Color = "red" },
            new Apple { Type = "apple", Color = "green" },
            new Banana { Type = "banana", Age = 1 },
            new Banana { Type = "banana", Age = 2 }
        });
    }
}

public class Fruit
{
    public string Type { get; set; }
}

public class Banana : Fruit
{
    public int Age { get; set; }
}

public class Apple : Fruit
{
    public string Color { get; set; }
}

public class FruitConverter : JsonInheritanceConverter
{
    public FruitConverter(string name) : base(name)
    {

    }

    public override string GetDiscriminatorValue(Type type)
    {
        return type switch
        {
            { } when type == typeof(Banana) => "banana",
            { } when type == typeof(Apple) => "apple",
            _ => throw new NotImplementedException(),
        };
    }

    protected override Type GetDiscriminatorType(JObject jObject, Type objectType, string discriminatorValue)
    {
        return discriminatorValue switch
        {
            "banana" => typeof(Banana),
            "apple" => typeof(Apple)
        };
    }
}

That's the code I'm playing around with, yet the Banana and Apple are not added in the open API schema unless I add KnownType to Fruit. Also looks like even the converter will not add the discriminator in the open API unless via Attribute.

Using it like this will not work:

.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.Converters.Add(new FruitConverter("type"));
})
My Champions Pool
@mychampionspool
is anyone using nSwag with an angular front end that uses strict: true in tscong.json? I am wondering what are the best practices for this?
chupavn
@chupavn
Hi, is it possible to ignore all delete method?
Rico Suter
@RicoSuter

Hi, is it possible to ignore all delete method?

Register a custom operation processor where you return false for all delete operations (exclude them)

Ghimpu Lucian Eduard
@GhimpuLucianEduard
@chupavn I think it’s doable with a custom operation processor https://github.com/RicoSuter/NSwag/wiki/Document-Processors-and-Operation-Processors, you could check if the operation is a deete, and not add it to the document or something lime that
Rico Suter
@RicoSuter
@GhimpuLucianEduard KnownTypeAttributes or JsonInheritanceAttributes are required so that the generator knows what types are possible (the switch is procedural and cannot be reflected.
@mychampionspool What is not working with strict: true? I think it should (mostly?) generate strict TS... otherwise turn strict off for the generated code (it's generated anyway, no need to check).
@GhimpuLucianEduard but KnownTypeAttribute also supports a string parameter where you can define a static method where you look up the types at runtime (fancy stuff):
https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.knowntypeattribute.-ctor?view=net-5.0#System_Runtime_Serialization_KnownTypeAttribute__ctor_System_String_
Ghimpu Lucian Eduard
@GhimpuLucianEduard
@RicoSuter yeah I see. My use case was that my models were part of domain and I did not want to add attributes to them. Ended up adding dto models and adding the atributes to those.
Rico Suter
@RicoSuter
ah so you wanted to define the inheritance completely "from outside"?
this is currently not supported (or you need to do the mapping yourself), main reason is that in order that inheritance works you not only need the correct spec, but also the correct serialization behavior (ie the discriminator property read and written)
Ghimpu Lucian Eduard
@GhimpuLucianEduard
Yeah exactly “from outside”. Yeah makes sense
My goal was to keep all serialization logic outside the domain part of the app, so it kinda made sense to add DTOs and map those to the domain models
Doug Bunting
@dougbu
@RicoSuter, I've been contacted indirectly by a customer reporting problems generating code for a JSON file in Visual Studio. The errors look very similar to problems I see when using NSwag.ApiDescription.Client v13.0.5 and an @(OpenApiReference) element.
  System.InvalidOperationException: Error while rendering Liquid template CSharp/Client.Class:
  System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Sequence contains more than one matching element
     at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
     at NSwag.OpenApiResponse.IsBinary(OpenApiOperation operation) in C:\projects\nswag\src\NSwag.Core\OpenApiResponse.cs:line 120
     at NSwag.OpenApiResponse.IsEmpty(OpenApiOperation operation) in C:\projects\nswag\src\NSwag.Core\OpenApiResponse.cs:line 164
     at NSwag.CodeGeneration.Models.OperationModelBase`2.get_UnwrappedResultType() in C:\projects\nswag\src\NSwag.CodeGeneration\Models\OperationModelBase.cs:line 108
     at NSwag.CodeGeneration.CSharp.Models.CSharpOperationModel.get_ResultType() in C:\projects\nswag\src\NSwag.CodeGeneration.CSharp\Models\CSharpOperationModel.cs:line 131
     --- End of inner exception stack trace ---
     at DotLiquid.Context.HandleError(Exception ex)
     at DotLiquid.Block.RenderAll(List`1 list, Context context, TextWriter result)
     at DotLiquid.Document.Render(Context context, TextWriter result)
     at DotLiquid.Template.RenderInternal(TextWriter result, RenderParameters parameters)
     at DotLiquid.Template.Render(TextWriter writer, RenderParameters parameters)
     at DotLiquid.Template.Render(RenderParameters parameters)
     at NJsonSchema.CodeGeneration.DefaultTemplateFactory.LiquidTemplate.Render() ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Sequence contains more than one matching element
     at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
     at NSwag.OpenApiResponse.IsBinary(OpenApiOperation operation) in C:\projects\nswag\src\NSwag.Core\OpenApiResponse.cs:line 120
     at NSwag.OpenApiResponse.IsEmpty(OpenApiOperation operation) in C:\projects\nswag\src\NSwag.Core\OpenApiResponse.cs:line 164
     at NSwag.CodeGeneration.Models.OperationModelBase`2.get_UnwrappedResultType() in C:\projects\nswag\src\NSwag.CodeGeneration\Models\OperationModelBase.cs:line 108
     at NSwag.CodeGeneration.CSharp.Models.CSharpOperationModel.get_ResultType() in C:\projects\nswag\src\NSwag.CodeGeneration.CSharp\Models\CSharpOperationModel.cs:line 131
     --- End of inner exception stack trace ---
     at DotLiquid.Context.HandleError(Exception ex)
     at DotLiquid.Block.RenderAll(List`1 list, Context context, TextWriter result)
     at DotLiquid.Document.Render(Context context, TextWriter result)
     at DotLiquid.Template.RenderInternal(TextWriter result, RenderParameters parameters)
     at DotLiquid.Template.Render(TextWriter writer, RenderParameters parameters)
     at DotLiquid.Template.Render(RenderParameters parameters)
     at NJsonSchema.CodeGeneration.DefaultTemplateFactory.LiquidTemplate.Render()
     --- End of inner exception stack trace ---
     at NJsonSchema.CodeGeneration.DefaultTemplateFactory.LiquidTemplate.Render()
     at NSwag.CodeGeneration.CSharp.CSharpClientGenerator.GenerateClientTypes(String controllerName, String controllerClassName, IEnumerable`1 operations)+MoveNext()
     at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
     at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
     at NSwag.CodeGeneration.ClientGeneratorBase`3.GenerateAllClientTypes() in C:\projects\nswag\src\NSwag.CodeGeneration\ClientGeneratorBase.cs:line 112
     at NSwag.CodeGeneration.ClientGeneratorBase`3.GenerateFile(ClientGeneratorOutputType outputType) in C:\projects\nswag\src\NSwag.CodeGeneration\ClientGeneratorBase.cs:line 73
Do you have any suggestions:grey_question: If not, how best to give you they OpenAPI JSON file we're testing with?