What is NSwag "client"?
I'm a Java tester and I've been moved to C# team. I was going to help my team with an integration backend testing. They use NSwag for generation "clients" and use it in tests. The problem for me is to understand what exactly it is that "client". I understand a client as e.g. browser which calls requests to server. What does "a client" mean regarding NSwag? Can anyone help and try to explain that to me as much simple as you can?
See also questions close to this topic
-
Huge amount of logon attempts when loading a page (without cache)
I notice in the Performance Monitor of Windows Server 2012 that there are spikes in logon attempts per second under Web Service -> Logon Attempts/sec. These spikes go from about 0 to 50.
I've traced this down to a page refresh. Loading a page with no cache that is. An average page load does about 50 requests (images, scripts, etc). Now apparently these 50 requests are shown as logon attempts.
Is this normal?
Note that this page does not require the visitor to be logged in.
-
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3\
When warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
No XML encryptor configured. Key {e43b756a-2818-4898-8730-5e8e0f230be7} may be persisted to storage in unencrypted form.
info: IdentityServer4.Startup[0]
Starting IdentityServer4 version 4.1.1+cebd52f5bc61bdefc262fd20739d4d087c6f961f
info: IdentityServer4.Startup[0]
You are using the in-memory version of the persisted grant store. This will store consent decisions, authorization codes, refresh and reference tokens in memory only. If you are using any of those features in production, you want to switch to a different store implementation.
info: IdentityServer4.Startup[0]
Using the default authentication scheme Identity.Application for IdentityServer
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://[::]:8081
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:8080
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: /app
info: IdentityServer4.Hosting.IdentityServerMiddleware[0]
Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
info: IdentityServer4.AspNetIdentity.ResourceOwnerPasswordValidator[0]
Credentials validated for username: muthu
info: IdentityServer4.Validation.TokenRequestValidator[0]
Token request validation success, {
"ClientId": "sdgfsdsgsdg",
"ClientName": "Swagger UI",
"GrantType": "password",
"Scopes": "api",
"AuthorizationCode": "********",
"RefreshToken": "********",
"UserName": "sample",
"Raw": {
"grant_type": "password",
"username": "sample",
"password": "REDACTED"
}
}
fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
Exception occurred while processing message.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
fail: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[0]
IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
---> System.IO.IOException: IDX20804: Unable to retrieve document from: 'http://*:8080/.well-known/openid-configuration'.
---> System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String address, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String address, IDocumentRetriever retriever, CancellationToken cancel)
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken cancel)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.HandleAuthenticateAsync()
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[7]
Bearer was not authenticated. Failure message: IDX20803: Unable to obtain configuration from: 'http://*:8080/.well-known/openid-configuration'.
info: IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler[12]
AuthenticationScheme: Bearer was challenged.
-
ASP.NET using return RedirectToAction(" ", " ") how to use this to redirect to a cshtml
I can not find a useable tutorial that explains how to redirect using REdirectToAction. can someone share a link that that explains ALL the steps needed to use this? I think I am having a hard time understanding how the parameters are given can find an HTML file with a model in the parameter? or is it a controller? I am very lost on how they communicate. please someone if you can help.
-
Testing Controller and Service in Jest
I'm fairly new to Jest and have been trying (with no luck) to figure out how to write tests for my controller. I'm not sure how to write the test as it calls another function. It would be great if I could get pointed in the right direction at least. Thanks in advance.
controller.ts
import * as Services from './services'; export async function GetCountriesList(req: Request, res: Response): Promise<void> { const response = await Services.GetCountriesList(); res.status(response.code).json({ status: response.status, message: response.message, count: response.count, data: response.data }); }
service.ts
import db from '../../modules/db'; import { DBGenericDataResponse } from '../../types/models'; export async function GetCountriesList(): Promise<DBGenericDataResponse> { const lQuery = 'somquery'; const responseMessage: DBGenericDataResponse = { code: 200, status: 'ok', message: '', count: 0, data: [], error: '' }; try { const dbResult = await db.query<any>(lQuery); responseMessage.message = 'Countries returned'; responseMessage.count = dbResult.rows.length; responseMessage.data = dbResult.rows; } catch (err) { responseMessage.code = 400; responseMessage.status = 'error'; responseMessage.message = 'Error retrieving Countries List'; responseMessage.error = err; } return responseMessage; }
-
How to unit test whether form validations are added dynamically in Jest?
I'm struggling with how to write a unit test for checking if my form validations were added to a FormControl in Angular.
It's a simple form with a
phone
field. I subscribe to that field and add or remove a validator depending on the field being empty or not. The code works as intended but I don't get how to test the subscription and valueChanges portion.How can I write a Jest test to cover the following subscription?
this.form = new FormGroup({ name: new FormControl('', [Validators.required]), phone: new FormControl(''), )} // Validate that phone is either blank or a valid phone number this.form.controls.phone.valueChanges.subscribe(data => { if (data.phone !== '') { // Add validations to phone this.form.controls.phone.setValidators([Validators.pattern(PHONE_VALIDATOR)]); } else { // Remove validation from phone when field is blank this.form.controls.phone.clearValidators(); } });
Best Attempt at Testing. It passes but my coverage is showing 0% for the .valueChanges section.
it('should add phone validation when phone is not blank', () => { component.ngOnInit(); let phoneField = component.form.controls.phone; phoneField.setValidators([Validators.pattern(PHONE_VALIDATOR), beetweenxAndyNumericChars(7, 11, false)]); phoneField.setValue('123'); component.save(); expect(phoneField.valid).toBeFalsy(); });
The above test runs but doesn't improve my code coverage. I'm stuck on how to improve the code coverage
-
junit nested mock injections for characterization tests
I need to be able to mock nested classes that have been injected using JUnit so I can create characterization tests. The problem is:
class 1 is using an object of class 2 and class 2 is using an object of class 3. And class 3 object is null when test is run on a class 1 method
this is the class structure I have:
class 1 { @Inject private Class2 class2 ; } class 2 { @Inject private Class3 class3 ; }
my test suite needs to run from the top down in order to fully test my system as it is an old system and I need to write tests starting from the top in order to gradually refactor it.
Test suite:
@RunWith(MockitoJUnitRunner.class) public class Class1Test { @Mock Class3 class3;//this doesn't work object remains null inside of mocked class2 @Mock Class2 class2; //this injection works and the object isn't null inside of class1 @InjectMocks public Class1 class1; @Before public void init() { MockitoAnnotations.initMocks(this); } @Test public void testFunction() { assertNotNull(class1.exampleFunction()); } }
I know the correct way is to stub dependencies, but this codebase is far too large to have to write unit tests for every layer, I need to be able to write tests in JUnit so that way I can run these tests while refactoring the codebase to make sure I haven't broken anything, hence why I haven't used postman since I need it to be quick.
on java 8 @inject is a java annotation using JUnit 4 but I think I can use junit5 if I need to. the project is a j2ee (java ee ) application
-
Returning a JWT token in a httponly cookie from a asp.net web api service
I have inherited a web api service and I have been tasked with updating the authentication such that the JWT token that is being generated for authentication is inserted into a
httponly
cookie, which is then used in a legacy AngularJS front end. Currently, we are not doing this, I've tried to find a decent example, but everything I can find is for .net core.The impetus to all of this is that we had a penetration test vendor advise us to insert the JWT token and other sensitive data into a
httponly
cookie.Long story short: Given the current code provided below, is there a way to insert the JWT token into a
httponly
cookie? If more information is needed, let me know and I can provide more explanation. Thanks.In Startup.cs:
public void ConfigureOAuth(IAppBuilder app) { app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); string issuer = ConfigurationManager.AppSettings["jwtissuer"]; int expireHour = Convert.ToInt32(ConfigurationManager.AppSettings["expirehour"]); var oAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(expireHour), Provider = new ApplicationAuthorizationServerProvider(), RefreshTokenProvider = new ApplicationRefreshTokenProvider(), AccessTokenFormat = new JwtTokenFormat(issuer), }; const string clientId = Constants.AMSClientId; var authRepository = new AuthRepository(); var destinationclient = authRepository.FindClient(clientId); if (destinationclient != null) { var secret = TextEncodings.Base64Url.Decode(destinationclient.Secret); // Authorization & Refresh Token Provider registration app.UseOAuthAuthorizationServer(oAuthServerOptions); //Resource Server app.UseJwtBearerAuthentication( new JwtBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AllowedAudiences = new[] { clientId }, IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] { new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret) } }); } }
We have overridden certain methods in OAuthAuthorizationServerProvider in a method called ApplicationAuthorizationServerProvider:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var ip = GetClientIpAddressFromHeader(context); if (ip == null) { return; } var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin") ?? "*"; context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin }); using (var repo = new AuthRepository()) { //Abbreviated nonessential code var languageCode = InternalServiceProxy.Invoke(c => c.GetLanguage(user.UserID).LanguageCode); var identity = new ClaimsIdentity("JWT"); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); identity.AddClaim(new Claim(ClaimTypes.PrimarySid, user.UserID.ToString())); identity.AddClaim(new Claim(CustomClaimTypes.PreferedLanguage, languageCode)); identity.AddClaims(ExtendedClaimsProvider.GetClaims(user)); //Additional params are not required for refresh token var serializedUser = JsonConvert.SerializeObject(user); var props = new AuthenticationProperties(new Dictionary<string, string> { { "as:client_id", context.ClientId ?? string.Empty }, { "userName", context.UserName }, { "Role", string.Join(",",user.Role) }, { "UserInfo", serializedUser }, { CustomClaimTypes.PreferedLanguage, languageCode } }); var ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } }
-
Failed on debugging ASP.Net in VS Code Mac
I tried to debug the ASP.Net web API project (I just created it without changing anything).
I followed Microsoft's tutorial, and I did manage to run it on docker.
https://code.visualstudio.com/docs/containers/quickstart-aspnet-core
I couldn't reload the image each time I made a change in the files, so I had to delete the old image and create a new one instead for each change.
I believe there's a better solution, but I couldn't find one. (if you have one, please share).
I then tried to debug the app with .Net Core Launch(web), but the browser didn't lunch, and I got many errors.
Most of the errors were related to JMC, so I added"justMyCode":false
to thelaunch.json
file.
I then got many"Cannot find or open the PDB file"
errors, although I checked a few of them and the files exist in the specific path.
In one of the forums, someone suggested adding:,"logging": { "moduleLoad": false }
But it just ignore the errors and didn't lunch anything.
here's the
launch.json
file:{ "version": "0.2.0", "configurations": [ { "name": ".NET Core Launch (web)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", "program": "${workspaceFolder}/stocks-api/bin/Debug/netcoreapp3.1/stocks-api.dll", "justMyCode":false, "args": [], "cwd": "${workspaceFolder}/stocks-api", "stopAtEntry": false, "serverReadyAction": { "action": "openExternally", "pattern": "\\\\bNow listening on:\\\\s+(https?://\\\\S+)" }, "env": { "ASPNETCORE_ENVIRONMENT": "Development" }, "sourceFileMap": { "/Views": "${workspaceFolder}/Views" } }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", "processId": "${command:pickProcess}" }, { "name": "Docker .NET Core Launch", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "netCore": { "appProject": "${workspaceFolder}/stocks-api/stocks-api.csproj" } } ] }
So I need your help finding a solution for the docker, and a solution for the web launch.
Thanks!
- How to make customize html table
-
System Design, Low level Design, High Level Design - never ending questions
I have gone through System Design, Low level Design & High Level Design questions. There are so many questions I wonder how to thorugh prepare these many questions in limited time for interview preparation. I know the systematic process to be followed for quality preparation but again it takes time.
Please suggest your approach or idea on this.
-
Is There Any Source For Performance Benchmarks of API Frameworks
I'm building a REST API and i'm trying to make is as fast as i can.
After a little research i found lots of Frameworks to create API, but i couldnt find a comparison of that Frameworks Performance Benchmarks.
Is There Any Source For Performance Benchmarks of API Frameworks?
So i can compare them as futures, speed benchmarks etc...
Some of the Frameworks that i've read about:
- Python (Django, Flask)
- Node.js (Express.js)
- Go
- Ruby
- PHP
If there is a source to compare those kind of Frameworks, it would be nice to have.
-
How best to inject async client/request configuration into NSwag client code
We are using NSwag generated client code for a web API. The API requires an Authorization header to be set on all requests.
This header value needs to be generated from async library methods (
ITokenAcquisition.GetAccessTokenForUserAsync()
in case it matters).So far the best option we've come up with is to create a class that implements
public Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
wrapping an
HTTPClient
, which would allow us to get the token and set the header before callingSendAsync
on the wrappedHttpClient
. We can then inject that class as the HttpClient used by the NSwag code.I don't think we can use NSwag's
CreateHttpClientAsync
because I can't see how to inject theITokenAcquisition
(and other dependencies) into the base class. (Unless the client generation code is cleverer than I'm giving it credit for)Have we missed something?
-
NSwag Not Recognizing Custom Authorization Attributes
Currently having a problem with NSwag generation on a custom authorize attribute. I have been completely unable to find anything on this issue elsewhere.
I've created a custom attribute for my WebAPI and more or less followed the patterns recommended here
internal class AuthorizeWithPermissionAttribute : AuthorizeAttribute { const string POLICY_PREFIX = "HasPermission"; public AuthorizeWithPermissionAttribute(string permission) { // logic excluded for brevity } public string Permission { get { // code } set { // code } } }
Then I decorate my controller with this attribute like so
[AuthorizeWithPermission("MY_PERMISSION_NAME")] public class MyController: ControllerBase { // Controller logic. }
So far I have tried
- Creating a public parameterless constructor on the attribute
- Changing the type (enum, int, string) of the constructor param
- Applying
[OpenApiIgnore]
to the type and then writing a custom filter inStartup.cs
when that didn't work - Changing the access modifier at the class and property level
- Applying the attribute broadly to the controller and methods directly.
Here is the error I'm getting:
Executing file 'nswag.json' with variables 'Configuration=Debug'... 3> Launcher directory: %UserDirectory%\.nuget\packages\nswag.msbuild\13.8.2\tools\NetCore31 3> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. 3> ---> System.NullReferenceException: Object reference not set to an instance of an object. 3> at %SLNNAME%.Authorization.Attributes.AuthorizeWithPermissionAttribute..ctor(String permission) in %SLNDirectory%\Authorization\Attributes\AuthorizeWithPermissionAttribute.cs:line 14 3> at System.Reflection.CustomAttribute._CreateCaObject(RuntimeModule pModule, RuntimeType type, IRuntimeMethodInfo pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs) 3> at System.Reflection.CustomAttribute.CreateCaObject(RuntimeModule module, RuntimeType type, IRuntimeMethodInfo ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs) 3> at System.Reflection.CustomAttribute.AddCustomAttributes(ListBuilder`1& attributes, RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, ListBuilder`1 derivedAttributes) 3> at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType) 3> at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit) 3> at System.RuntimeType.GetCustomAttributes(Boolean inherit) 3> at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.CreateControllerModel(TypeInfo typeInfo) 3> at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.OnProvidersExecuting(ApplicationModelProviderContext context) 3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.CreateApplicationModel(IEnumerable`1 controllerTypes) 3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors() 3> at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context) 3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection() 3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize() 3> at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.get_ActionDescriptors() 3> at Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionGroupCollectionProvider.get_ApiDescriptionGroups() 3> at NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator.GenerateAsync(Object serviceProvider) 3> at NSwag.AspNetCore.OpenApiDocumentProvider.GenerateAsync(String documentName) 3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.GenerateDocumentWithDocumentProviderAsync(IServiceProvider serviceProvider) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 287 3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.GenerateDocumentAsync(AssemblyLoader assemblyLoader, IServiceProvider serviceProvider, String currentWorkingDirectory) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 276 3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.<>c__DisplayClass0_0.<<Process>b__0>d.MoveNext() in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 30 3> --- End of stack trace from previous location where exception was thrown --- 3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 29 3> --- End of inner exception stack trace --- 3> at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions) 3> at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 3> at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) 3> at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in C:\projects\nswag\src\NSwag.AspNetCore.Launcher\Program.cs:line 170 3> System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'. 3> at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 221 3> at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocumentBase.cs:line 280 3> at NSwag.Commands.NSwagDocument.ExecuteAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocument.cs:line 81 3> at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 86 3> at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 32 3> at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input) 3> at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input) 3> at NConsole.CommandLineProcessor.Process(String[] args, Object input) 3> at NSwag.Commands.NSwagCommandProcessor.Process(String[] args) in C:\projects\nswag\src\NSwag.Commands\NSwagCommandProcessor.cs:line 56 3> %SLNDirectory%.csproj(59,5): error MSB3073: The command "dotnet "%UserDirectory%\.nuget\packages\nswag.msbuild\13.8.2\build\../tools/NetCore31/dotnet-nswag.dll" run nswag.json /variables:Configuration=Debug" exited with code -1. 3> Done executing task "Exec" -- FAILED.
-
using .net nSwag auto generated typescript classes with "strict": true in tsconfig.json
I have a simple proof of concept app that has a todo list (how original haha).
This is a .net core 5 app with an angular front end. I use nSwag to auto generate the .ts classes/api endpoints that is consumed by the angular app.The problem is that I am trying to use the strict mode of typescript and the classes that are generated have lots of " | undefined" added to the class types.
ie:
export class TodosVm implements ITodosVm { priorityLevels?: PriorityLevelDto[] | undefined; lists?: TodoListDto[] | undefined;
which is auto generated from the following c# class:
public class TodosVm { public IList<PriorityLevelDto> PriorityLevels { get; set; } public IList<TodoListDto> Lists { get; set; } }
the "lists" are being marked as optional with the
| undefined
and?:
As a result this generates a lot of errors in the angular complier:
Object is possibly 'undefined'.
I am wondering what is the best way to handle this other than creating object initializers in all of my angular components. Does nSwag have a setting to help with this?
Thanks