nSwag Client: Is there a better/easier approach to affect PropertyNameCaseInsensitive?
We are attempting to integrate System.Text.Json into our REST API and rest clients, previously using Newtonsoft.
We are using nswag CSharpClientGenerator.GenerateFile to generate our REST API clients via code (not nSwag Studio).
Because of the casing differences between the property names and the json name, items are not correctly deserializing. We have been able to over come this by setting PropertyNameCaseInsensitive = true.
We were able to do this via a partial class as below:
partial class MakeClient
{
partial void UpdateJsonSerializerSettings(JsonSerializerOptions settings)
{
settings.PropertyNameCaseInsensitive = true;
}
}
I really don't want to create these partial classes for every client.
Is there an easier way to do this, such as injecting JsonSerializerOptions into the client, or some type of global setting?
do you know?
how many words do you know
See also questions close to this topic
-
site only opens in CefSharp
zaakr.net is a site can be opened only in zaakr.exe application or through android(.apk), when opened in browser u been redirected to https://browser.zaakr.net so u download there application, (.exe) file is using cefsharp as a browser so it can access website, from 2 month i could open it from chromium as cefsharp uses chromium, now i can't access website through chromium for some reason idk, i even made a cefsharp browser myself using visual studio nothing worked all the time i been redirected to browser.zaakr.com, i want to access through any browser that have devtools available for a project, note that application zaakr.exe is still using cefsharp even the older version still can access site. i would appreciate any help, sry for any spelling mistakes, thanks.
-
C# MariaDB Update Function working in DataStore but not updating in .NET Application
My initial issue is that my database does not update when I call on this specific code. I am not sure if it is C# itself or the update query that I am calling.
string _connectionString = "validConnectionstring"; using (MySqlConnection _mySqlConnection = new MySqlConnection(_connectionString) { _mySqlConnection.Open(); using (MySqlCommand command = new MySqlCommand("UpdateProfileStatus", _mySqlConnection)) { command.Transaction = _mySqlConnection.BeginTransaction(); command.CommandTimeout = TimeSpan.FromSeconds(60).Seconds; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@_username", "test"); command.Parameters.AddWithValue("@_status", true); command.ExecuteNonQuery(); } _mySqlConnection.Close(); }
I get no updates in my database but my console logs that the query is executed returning the value of 1 but there is no update that actually happens in my DB. Is there something in my code to reason why it is failing?
Here is the stored procedure that I have for the update command
CREATE PROCEDURE UpdateProfileStatus(_username VARCHAR(25), _status BOOL) UPDATE Profile SET status = _status WHERE username = _username;
I know the Stored Procedure works but am not sure why my .NET application is not responding to my procedure call. Is it something to do with my implementation of the parameters or is it my procedure itself?
-
How to add a new Model visually in Mac OS visual Studio
I do not see any choice to create a model in Mac visual studio? I In the windows version the Class created with its imports
using Linq
using Threading.Tasks
using Collection.Generic
-
DELETE operation javascript fetch() with REST API firebase
I use the following API request in order to delete all texts (so called cps) of one section (one section contains many cps)
await fetch(`https://12345-default-rtdb.europe- west1.firebasedatabase.app/cps/${userId}.json?section_id=${mysection}`,{method:'DELETE', // });
userId is correct, mysections is the current sectionId, section_id is the key of the sectionId in the JSON document. (eg: -N09gWdyQlV7OsPpEx7t or -N09g_HjbcFCQFBiIX0A see below) In this example all cps of all sections are being deleted. So the conditional query does not work.
What is going wrong here? Thanks!
The tree within firestore looks like this:
cps -> user1 -> -N09gWdyQlV7OsPpEx7t
cps -> user1 -> -N09g_HjbcFCQFBiIX0A
....
-
OAuth 2.0 flow using Keycloak with a back-end and front-end?
I'm working on a project that consists of:
- A back-end in Java (JEE project deployed on Wildfly)
- Front-end developed in Angular
- Keycloak for authorization and authentication
What I need to do is:
- Access my Angular app, which communicates with my backend calling its APIs(e.g GET, POST, PUT, DELETE)
- Go to the Login Page, authentication is done by Keycloak, so I get directed to Keycloak login page.
- Login is successfull ----> I get redirected to my Angular landing page, now I can navigate my Angular app.
The frontend is talking with the backend via RESTful APIs, and I need to use OAuth2.0/OPENID standard flow, which means I'm gonna first get the auth code and the the access token/refresh token to stay connected.
My backend is already configurated with Keycloak through the Wildfly adapter given on Keycloak official site, and through web.xml and keycloak.json both in WEB-INF folder.
So known that I'm able to get the auth code via the Valid Redirect URIs given by Keycloak, how can I configure my whole project to get the 3 points written above? Do I need two clients on my Realm in Keycloak?
Can someone please explain me how I can I setup the whole flow using Keycloak?
Thanks a lot!
-
REST client API data types with laravel
What form of data should I choose as input for a rest api with laravel? form-data, raw, urlencoded or others?
-
Is an OpenAPI path with multiple variables in the same segment valid?
Is the following valid?
GET image/{id}/{palette}.{file_extension}
I want to be able to do something like this: example:
GET image/1/falsecolor.jpg GET image/4/alternative.png GET image/9/falsecolor.tiff
Basically, the palette defines how is the image is colored (color palette) and the extension is the file format better suited for your application (mobile deals best with one file format, web with another, etc), all OpenAPI linters I tried do validate it, there is nothing that I can find in the documentation for the OpenAPI that says that this is not a valid approach, but when I uploaded this to Postman, it borked beyond recognition, loading the palette and the file extension both as collection variables instead of API properties, and Postman is supposedly OpenAPI compliant/compatible, so I am wondering if this is actually a non-compliant path parameter.
-
AWS API Gateway: Why setting "application/json" mapping template for GET request is required for MOCK integration to work?
I'm setting up a mock integration for GET requests with AWS API Gateway, and wonder why it only works when the
application/json
request template is specified. To my understanding GET request does not have a body and hence does not have a Content-Type header. What is special about 'application/json'? Is this behavior documented somewhere or am I missing some defaults somewhere?Here is terraform code for my API Gateway:
resource "aws_api_gateway_rest_api" "test-api" { name = "test-api" endpoint_configuration { types = ["REGIONAL"] } body = jsonencode(yamldecode(file("openapi.yaml"))) }
openapi: "3.0.1" info: version: "1.0" title: example paths: /test: get: responses: "200": description: demo headers: Content-Type: { schema: { type: 'string' } } x-amazon-apigateway-integration: type: MOCK passthroughBehavior: when_no_templates # the next line is required. # API Gateway returns 500 error if I remove it. why? # API Gateway returns 415 error if I change application/json to text/plain. why? requestTemplates: { 'application/json': '{"statusCode": 200}' } responses: default: statusCode: 200 responseParameters: { 'method.response.header.Content-Type': "'text/plain'" } responseTemplates: {'text/plain': 'hello'}
Here is an example log output when requestTemplates is set to
{ 'text/plain': '{"statusCode": 200}' }
Execution log for request 09c6d06b-669c-4717-86a2-c8489136f760 Fri May 06 14:28:24 UTC 2022 : Starting execution for request: 09c6d06b-669c-4717-86a2-c8489136f760 Fri May 06 14:28:24 UTC 2022 : HTTP Method: GET, Resource Path: /test Fri May 06 14:28:24 UTC 2022 : Method request path: {} Fri May 06 14:28:24 UTC 2022 : Method request query string: {} Fri May 06 14:28:24 UTC 2022 : Method request headers: {} Fri May 06 14:28:24 UTC 2022 : Method request body before transformations: Fri May 06 14:28:24 UTC 2022 : Execution failed: null Fri May 06 14:28:24 UTC 2022 : Method completed with status: 415
-
Validate Requests in NSwag generated Client
I have a .NET 6 Webclient and REST Contract, that is generated from a YAML with NSwag. The contract contains some validation properties. Is there any way to validate my request on the client side? I don't want to write the validation code by hand. In the NSwag documentation I only found flags to generate validation attributes for generated controllers, but not for the web client.
YAML:
- name: anyField in: query description: Field with max value=20 and required required: true schema: maximum: 20 type: integer format: int32
Generated contract code:
/// <summary> /// Field with max value=20 and required /// </summary> [Newtonsoft.Json.JsonProperty("anyField", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public int AnyField{ get; set; }
-
ASP.NET Core 6 Web API with Angular
I have the following setup: ASP.NET Core 6 Web API with controllers and an Angular 13 frontend.
Some of my controllers will be used by external parties to integrate into my system, while other controllers is specifically for the angular UI. I would like to use NSwag to generate the typescript client for the Angular specific controllers, while I have a separate Swagger json url / specification I can use to give to external parties, that do not show the angular controllers.
IE I need two sets / urls of swagger in the same API project. Can anyone perhaps help on how to configure swagger for this configuration?
Any advise would be greatly appreciated.
-
How to reuse classes when generating an OpenAPI client?
Let's say I have this class defined:
public class Animal { public int RegId {get;set;} public string Name {get;set;} }
And I need to expose it to an remote part of my system ( a client app in another location, for example ) and I decided to use OpenAPI to make the communication.
The controller code is something like:
[HttpGet("GetLivingCargo")] public async Task<IEnumerable<Animal>> GetLivingCargo() { return await pFacade.GetLivingCargo(); }
Swagger generates the documentation all well. When I generate the API client to use in the remote app, all times I have that class duplicated (so there's my original class and the generated client's exactly equal class).
How I can avoid it, without having to manually write the API client myself to use my original class?
-
Incorrect method signature generated from OpenAPI definition
I just took over a project about a ticketing system and have inherited the following OpenAPI specification.
openapi: '3.0.2' info: title: Tickets Management version: '1.0' paths: /tickets: post: tags: - Create ticket # Commented out code will generate controller method taking a NewTicket # requestBody: # required: true # content: # application/json: # schema: # $ref: '#/components/parameters/newTicket' requestBody: #The following will generate a controller method taking an object $ref: '#/components/requestBodies/newTicket' operationId: CreateTicket responses: 200: $ref: '#/components/responses/ticketId' default: $ref: '#/components/responses/default' components: parameters: newTicket: name: newTicket in: path required: true schema: $ref: '#/components/schemas/newTicket' requestBodies: newTicket: description: Create a new ticket required: true content: application/json: schema: $ref: '#/components/schemas/newTicket' schemas: uuid: title: uuid type: string format: uuid pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' minLength: 36 maxLength: 36 shortText: title: shortText type: string pattern: ^[\s\S]+$ example: "Any valid text" minLength: 1 maxLength: 128 newTicket: title: Input for creating a new ticket description: Foobar type: object required: - ticketDescription properties: creator: ticketDescription: Description of the ticket $ref: '#/components/schemas/shortText' responses: ticketId: description: Successfully created a new ticket. content: application/json: schema: $ref: '#/components/schemas/uuid' 200: description: Ok content: application/json: schema: title: Ok type: string example: Ok default: description: Default content: application/json: schema: title: Request not found type: string example: Not found
When I generate C# code, .NET 6, using NSwagStudio or Unchase OpenAPI, I get the following method for creating a new ticket:
public virtual System.Threading.Tasks.Task<System.Guid> CreateTicketAsync(object body) { return CreateTicketAsync(body, System.Threading.CancellationToken.None); }
As you can see, the body is of type object, which is wrong. If I instead modify the spec to point to #/components/parameters/newTicket (see commented out code in the spec), then the input parameter is of type
NewTicket
. Now, I prefer to point to#/components/requestBodies/..
instead of#/components/parameters/...
, but how should I do that and also get theNewTicket
in the method signature?PS: Also tried to past in the spec above into editor.swagger.io and it generates
public virtual IActionResult CreateTicket([FromBody]NewTicket body) { //Ommitted }
This looks better I don't want to return an
IActionResult
(seems to not be .NET 6.). Any suggestions? -
NSwagStudio nswag command line does this support TSlint / ESLint?
Is possible to generate an Angular code to match with ESlint/TSLint standards