From f4f2e365684acfdf4fe30ff807675e4fbd50c781 Mon Sep 17 00:00:00 2001 From: Zijian Date: Tue, 2 Jul 2024 08:23:56 +1000 Subject: [PATCH 1/5] yes --- .../src/clientapi/WebApiCoreNg2ClientAuto.ts | 583 ++--- AuthDbCreator/CreateBlankMySql.ps1 | 2 +- AuthEF.sln | 7 + Core3WebApi/CodeGen.json | 9 +- Core3WebApi/Controllers/AuthController.cs | 43 +- Core3WebApi/Core3WebApi.csproj | 1 - Core3WebApi/Helpers/ValidateModelAttribute.cs | 17 - Core3WebApi/Program.cs | 15 +- Core3WebApi/Properties/launchSettings.json | 2 - CoreWebApi.ClientApi/WebApiClientAuto.cs | 1891 ++++++++--------- .../AccountBindingModels.cs | 15 +- .../DemoWebApi.DemoDataCore.csproj | 4 - DemoWebApi.DemoDataCore/Entities.cs | 3 - .../Fonlow.WebApp.Accounts.csproj | 6 +- Fonlow.WebApp.Accounts/UsernameModel.cs | 36 +- PublishMySqlPluginToWebApi.ps1 | 4 +- Tests/AuthRemoteTests/AuthRemoteTests.csproj | 2 +- Tests/AuthTests/AuthTests.csproj | 2 +- Tests/AuthTests/TokenFacts.cs | 10 + .../IntegrationTestsCore.csproj | 2 +- .../PetStoreApiTests/PetStoreApiTests.csproj | 2 +- 21 files changed, 1087 insertions(+), 1569 deletions(-) delete mode 100644 Core3WebApi/Helpers/ValidateModelAttribute.cs diff --git a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts index 9a95e56..f485279 100644 --- a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts +++ b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts @@ -2,17 +2,149 @@ import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; export namespace DemoWebApi_Controllers_Client { + export interface Hero { + id?: string | null; + name?: string | null; + } + +} + +export namespace DemoWebApi_DemoData_Client { + export interface Entity { + addresses?: Array; + id?: string | null; + name: string; + phoneNumbers?: Array; + web?: string | null; + } + + export interface Person extends DemoWebApi_DemoData_Client.Entity { + baptised?: Date | null; + dob?: Date | null; + givenName?: string | null; + surname?: string | null; + } + + export interface Company extends DemoWebApi_DemoData_Client.Entity { + businessNumber?: string | null; + businessNumberType?: string | null; + foundDate?: Date | null; + registerDate?: Date | null; + textMatrix?: Array>; + int2D?: number[][]; + int2DJagged?: Array>; + lines?: Array; + } + + export enum Days { Sat = 1, Sun = 2, Mon = 3, Tue = 4, Wed = 5, Thu = 6, Fri = 7 } + + export interface MimsResult { + generatedAt?: Date | null; + message?: string | null; + result?: T; + success?: boolean | null; + } + + export interface MyGeneric { + myK?: K; + myT?: T; + myU?: U; + status?: string | null; + } + + export interface IdMap { + id?: string | null; + idNotEmitDefaultValue?: string | null; + nullableId?: string | null; + requiredName?: string | null; + text?: string | null; + } + + export interface MimsPackage { + kk?: number | null; + kK2?: number | null; + optionalEnum?: number | null; + optionalInt?: number | null; + result?: DemoWebApi_DemoData_Client.MimsResult; + tag?: string | null; + } + +} + +export namespace Core3WebApi_Controllers_Client { + @Injectable() + export class Statistics { + constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { + } + + /** + * GET api/Statistics/distribution + */ + getDistribution(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/Statistics/distribution', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + } + +} + +export namespace DemoCoreWeb_Controllers_Client { /** - * Complex hero type + * Authorize: Bearer */ - export interface Hero { + @Injectable() + export class SpecialTypes { + constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { + } - /** Type: long, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 */ - id?: string | null; - name?: string | null; + /** + * Anonymous Dynamic of C# + * GET api/SpecialTypes/AnonymousDynamic + * @return {any} dyanmic things + */ + getAnonymousDynamic(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousDynamic2 + */ + getAnonymousDynamic2(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousObject + */ + getAnonymousObject(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousObject2 + */ + getAnonymousObject2(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * POST api/SpecialTypes/AnonymousObject + */ + postAnonymousObject(obj: any, headersHandler?: () => HttpHeaders): Observable> { + return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); + } + + /** + * POST api/SpecialTypes/AnonymousObject2 + */ + postAnonymousObject2(obj: any, headersHandler?: () => HttpHeaders): Observable> { + return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject2', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); + } } +} + +export namespace DemoWebApi_Controllers_Client { /** * Manage user accounts stored in ASP.NET Core Identity database. @@ -589,6 +721,19 @@ export namespace DemoWebApi_Controllers_Client { } } + @Injectable() + export class Polymorphism { + constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { + } + + /** + * POST api/Polymorphism + */ + authenticate(model: Fonlow_AspNetCore_OAuth2_Client.RequestBase | null, headersHandler?: () => HttpHeaders): Observable { + return this.http.post(this.baseUri + 'api/Polymorphism', JSON.stringify(model), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }) }); + } + } + /** * For testing different commbinations of parameters and returns @@ -1340,332 +1485,37 @@ export namespace DemoWebApi_Controllers_Client { } -export namespace DemoWebApi_DemoData_Another_Client { - - /** - * 2D position - * with X and Y - * for Demo - */ - export interface MyPoint { - - /** - * X - * Type: double - */ - x: number; - - /** - * Y - * Type: double - */ - y: number; +export namespace Fonlow_AspNetCore_OAuth2_Client { + export interface RequestBase { + grantType: string; } } -export namespace DemoWebApi_DemoData_Client { - export interface Address { - city?: string | null; - country?: string | null; - - /** Type: GUID */ - id?: string | null; - postalCode?: string | null; - state?: string | null; - street1?: string | null; - street2?: string | null; - type?: DemoWebApi_DemoData_Client.AddressType | null; - - /** - * It is a field - */ - location?: DemoWebApi_DemoData_Another_Client.MyPoint; - } - - export enum AddressType { Postal, Residential } - - export interface Company extends DemoWebApi_DemoData_Client.Entity { - - /** - * BusinessNumber to be serialized as BusinessNum - */ - BusinessNum?: string | null; - businessNumberType?: string | null; - - /** Data type: Date */ - foundDate?: Date | null; - - /** Type: DateOnly */ - registerDate?: Date | null; - textMatrix?: Array>; - int2D?: number[][]; - int2DJagged?: Array>; - lines?: Array; - } - - export enum Days { - Sat = 1, - Sun = 2, - Mon = 3, - Tue = 4, - Wed = 5, - - /** - * Thursday - */ - Thu = 6, - Fri = 7 - } - - - /** - * Base class of company and person - */ - export interface Entity { - - /** - * Multiple addresses - */ - addresses?: Array; - id?: string | null; - - /** - * Name of the entity. - * Required - */ - name: string; - phoneNumbers?: Array; - - /** Type: Uri */ - web?: string | null; - } - - - /** - * To test different serializations against Guid - */ - export interface IdMap { - - /** Type: GUID */ - id?: string | null; - - /** Type: GUID */ - idNotEmitDefaultValue?: string | null; - nullableId?: string | null; - requiredName: string; - text?: string | null; - } - - export enum MedicalContraindiationResponseTypeReason { M = "Mm", S = "Ss", P = "Pp", I = "I", A = "A" } - - export enum MedicalContraindiationResponseTypeTypeCode { P = "P", T = "Tt" } - - export interface MimsPackage { - - /** - * Type: int - * Range: inclusive between 10 and 100 - */ - kk?: number | null; - - /** - * Having an initialized value in the property is not like defining a DefaultValueAttribute. Such intialization happens at run time, - * and there's no reliable way for a codegen to know if the value is declared by the programmer, or is actually the natural default value like 0. - * Type: int, -2,147,483,648 to 2,147,483,647 - */ - kK2?: number | null; - optionalEnum?: DemoWebApi_DemoData_Client.MyEnumType | null; - optionalInt?: number | null; - result?: DemoWebApi_DemoData_Client.MimsResult; - tag?: string | null; - } - - export interface MimsResult { - generatedAt?: Date | null; - message?: string | null; - result?: T; - success?: boolean | null; - } - - export enum MyEnumType { First = 1, Two = 2 } - - export interface MyGeneric { - myK?: K; - myT?: T; - myU?: U; - status?: string | null; - } - - export interface MyPeopleDic { - anotherDic?: {[id: string]: string }; - dic?: {[id: string]: DemoWebApi_DemoData_Client.Person }; - intDic?: {[id: number]: string }; - } - - export interface Person extends DemoWebApi_DemoData_Client.Entity { - - /** Data type: Date */ - baptised?: Date | null; - - /** - * Date of Birth. - * This is optional. - */ - dob?: Date | null; - givenName?: string | null; - surname?: string | null; - } - - export interface PhoneNumber { - fullNumber?: string | null; - phoneType?: DemoWebApi_DemoData_Client.PhoneType | null; - } - - - /** - * Phone type - * Tel, Mobile, Skyp and Fax - */ - export enum PhoneType { - - /** - * Land line - */ - Tel, - - /** - * Mobile phone - */ - Mobile, - Skype, - Fax - } - -} - -export namespace DemoWebApi_Models_Client { - export interface AddExternalLoginBindingModel { - - /** Required */ - externalAccessToken?: string | null; - } - - export interface ChangePasswordBindingModel { - - /** Data type: Password */ - confirmPassword?: string | null; - - /** - * Required - * String length: inclusive between 6 and 100 - * Data type: Password - */ - newPassword: string; - - /** - * Required - * Data type: Password - */ - OldPwd: string; - } - - export interface RegisterBindingModel { - - /** Data type: Password */ - confirmPassword?: string | null; - - /** Required */ - email?: string | null; - - /** - * Required - * String length: inclusive between 6 and 100 - * Data type: Password - */ - password?: string | null; - } - - export interface RegisterExternalBindingModel { - - /** Required */ +export namespace Fonlow_WebApp_Accounts_Client { + export interface UserInfoViewModel { + createdUtc?: Date | null; email?: string | null; - } - - export interface RemoveLoginBindingModel { - - /** Required */ + fullName?: string | null; + hasRegistered?: boolean | null; + id?: string | null; loginProvider?: string | null; - - /** Required */ - providerKey?: string | null; - } - - export interface SetPasswordBindingModel { - - /** Data type: Password */ - confirmPassword?: string | null; - - /** - * Required - * String length: inclusive between 6 and 100 - * Data type: Password - */ - newPassword?: string | null; - } - -} - -export namespace Fonlow_WebApp_Accounts_Client { - export interface AddExternalLoginBindingModel { - externalAccessToken?: string | null; - } - - export interface ApiKey { - expiryTime?: Date | null; - key?: string | null; + roles?: Array; + userName?: string | null; } export interface ChangePasswordBindingModel { confirmPassword?: string | null; - newPassword?: string | null; - oldPassword?: string | null; - } - - export interface CustomToken { - connectionId?: string | null; - stamp?: Date | null; - tokenValue?: string | null; - } - - export interface ExternalLoginViewModel { - name?: string | null; - state?: string | null; - url?: string | null; - } - - export interface ManageInfoViewModel { - email?: string | null; - externalLoginProviders?: Array; - localLoginProvider?: string | null; - logins?: Array; + newPassword: string; + oldPassword: string; } export interface RegisterBindingModel { confirmPassword?: string | null; email?: string | null; fullName?: string | null; - password?: string | null; - userName?: string | null; - } - - export interface RegisterExternalBindingModel { - email?: string | null; - } - - export interface RemoveLoginBindingModel { - loginProvider?: string | null; - providerKey?: string | null; + password: string; + userName: string; } export interface ResetPasswordViewModel { @@ -1677,113 +1527,12 @@ export namespace Fonlow_WebApp_Accounts_Client { export interface SetPasswordBindingModel { confirmPassword?: string | null; - newPassword?: string | null; + newPassword: string; } export interface SetUserPasswordBindingModel extends Fonlow_WebApp_Accounts_Client.SetPasswordBindingModel { userId?: string | null; } - export interface TokenResponseModel { - access_token: string; - connection_id?: string | null; - expires: string; - expires_in: number; - refresh_token?: string | null; - scope?: string | null; - state?: string | null; - token_type: string; - username: string; - } - - export interface UserInfoViewModel { - createdUtc?: Date | null; - email?: string | null; - fullName?: string | null; - hasRegistered?: boolean | null; - id: string; - loginProvider?: string | null; - roles?: Array; - userName: string; - } - - export interface UserLoginInfoViewModel { - loginProvider?: string | null; - providerKey?: string | null; - } - -} - -export namespace Core3WebApi_Controllers_Client { - @Injectable() - export class Statistics { - constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { - } - - /** - * GET api/Statistics/distribution - */ - getDistribution(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/Statistics/distribution', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - } - -} - -export namespace DemoCoreWeb_Controllers_Client { - - /** - * Authorize: Bearer - */ - @Injectable() - export class SpecialTypes { - constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { - } - - /** - * Anonymous Dynamic of C# - * GET api/SpecialTypes/AnonymousDynamic - * @return {any} dyanmic things - */ - getAnonymousDynamic(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousDynamic2 - */ - getAnonymousDynamic2(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousObject - */ - getAnonymousObject(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousObject2 - */ - getAnonymousObject2(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * POST api/SpecialTypes/AnonymousObject - */ - postAnonymousObject(obj: any, headersHandler?: () => HttpHeaders): Observable> { - return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); - } - - /** - * POST api/SpecialTypes/AnonymousObject2 - */ - postAnonymousObject2(obj: any, headersHandler?: () => HttpHeaders): Observable> { - return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject2', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); - } - } - } diff --git a/AuthDbCreator/CreateBlankMySql.ps1 b/AuthDbCreator/CreateBlankMySql.ps1 index 196f74c..da423fe 100644 --- a/AuthDbCreator/CreateBlankMySql.ps1 +++ b/AuthDbCreator/CreateBlankMySql.ps1 @@ -7,5 +7,5 @@ $RuntimeId = ([System.Runtime.InteropServices.RuntimeInformation]::RuntimeIdenti $ExecutableExt = If ($IsWindows) {".exe"} Else {""} dotnet publish ../Fonlow.EntityFrameworkCore.MySql/Fonlow.EntityFrameworkCore.MySql.csproj -r $RuntimeId --configuration Release --output bin/Release/$netVersion $connectionString = "server=localhost;port=3306;Uid=root; password=Secured321*; database=DemoAppAuth_Test; Persist Security Info=True;Allow User Variables=true" -$CreatorExe = "AuthDbCreator" + $ExecutableExt; +$CreatorExe = "AuthDbCreator" + $ExecutableExt Invoke-Expression "&./bin/Release/net8.0/$CreatorExe Fonlow.EntityFrameworkCore.MySql '$connectionString'" \ No newline at end of file diff --git a/AuthEF.sln b/AuthEF.sln index cf49d81..539d61f 100644 --- a/AuthEF.sln +++ b/AuthEF.sln @@ -60,6 +60,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PetStoreApiTests", "Tests\P EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fonlow.EntityFrameworkCore.PostgreSQL", "Fonlow.EntityFrameworkCore.PostgreSQL\Fonlow.EntityFrameworkCore.PostgreSQL.csproj", "{CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelsUnitTests", "Tests\ModelsUnitTests\ModelsUnitTests.csproj", "{22AC790B-B412-40BB-880F-468725DA3843}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -142,6 +144,10 @@ Global {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Debug|Any CPU.Build.0 = Debug|Any CPU {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Release|Any CPU.Build.0 = Release|Any CPU + {22AC790B-B412-40BB-880F-468725DA3843}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22AC790B-B412-40BB-880F-468725DA3843}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -162,6 +168,7 @@ Global {423C910B-96BB-4855-B3FB-94C060A3B8DA} = {39445712-FE9F-4406-A103-F181E9DC2233} {F91D9E0C-F235-44E1-A1DB-1213AF9663AB} = {39445712-FE9F-4406-A103-F181E9DC2233} {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B} = {03B8AB6F-9686-44AF-9AF1-6DCC6E742808} + {22AC790B-B412-40BB-880F-468725DA3843} = {39445712-FE9F-4406-A103-F181E9DC2233} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F3EFB0EB-BFFA-4C16-B235-B121695229EF} diff --git a/Core3WebApi/CodeGen.json b/Core3WebApi/CodeGen.json index 389ada4..d52bb08 100644 --- a/Core3WebApi/CodeGen.json +++ b/Core3WebApi/CodeGen.json @@ -2,13 +2,8 @@ "ApiSelections": { "ExcludedControllerNames": [ ], - - "DataModelAssemblyNames": [ - "DemoWebApi.DemoDataCore", - "Fonlow.WebApp.Accounts", - "Core3WebApi" - ], - "CherryPickingMethods": 3 + "DataModelAssemblyNames": [ "DemoWebApi.DemoDataCore", "Fonlow.WebApp.Accounts", "Core3WebApi", "Fonlow.AspNetCore.Identity" ], + "CherryPickingMethods": 32 }, "ClientApiOutputs": { diff --git a/Core3WebApi/Controllers/AuthController.cs b/Core3WebApi/Controllers/AuthController.cs index 5a49cbc..22f1ab3 100644 --- a/Core3WebApi/Controllers/AuthController.cs +++ b/Core3WebApi/Controllers/AuthController.cs @@ -1,4 +1,5 @@ using Fonlow.AspNetCore.Identity; +using Fonlow.AspNetCore.OAuth2; using Fonlow.WebApp.Accounts; using Fonlow.WebApp.Identity; using Microsoft.AspNetCore.Authorization; @@ -24,6 +25,7 @@ namespace WebApp.Controllers /// [ApiExplorerSettings(IgnoreApi = true)] [Route("token")] + //[ApiController] public class AuthController : ControllerBase { public ApplicationUserManager UserManager @@ -52,25 +54,44 @@ public AuthController(ApplicationUserManager userManager, SymmetricSecurityKey s [AllowAnonymous] [Consumes("application/x-www-form-urlencoded")] [HttpPost] - public async Task> Authenticate([FromForm] UsernameModel model) + public async Task> Authenticate([FromForm] RequestBase model) { - ApplicationUser user = await UserManager.FindByNameAsync(model.Username); - if (user == null) + if (model is ROPCRequst) { - return Unauthorized(new { message = "Username or password is invalid" }); - } + ROPCRequst ropcRequest = model as ROPCRequst; + ApplicationUser user = await UserManager.FindByNameAsync(ropcRequest.Username); + if (user == null) + { + return Unauthorized(new { message = "Username or password is invalid" }); + } - bool passwordIsCorrect = await UserManager.CheckPasswordAsync(user, model.Password); - if (!passwordIsCorrect) + bool passwordIsCorrect = await UserManager.CheckPasswordAsync(user, ropcRequest.Password); + if (!passwordIsCorrect) + { + return Unauthorized(new { message = "Username or password is incorrect" }); + } + + var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); + var newLoginConnectionId = Guid.NewGuid(); + return await tokenHelper.GenerateJwtToken(user, ropcRequest.Username, newLoginConnectionId); + } + else if (model is RefreshAccessTokenRequest) { - return Unauthorized(new { message = "Username or password is incorrect" }); + //RefreshAccessTokenRequest refreshAccessTokenRequest = model as RefreshAccessTokenRequest; + //var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); + //var tokenTextExisting = await tokenHelper.MatchToken(user, "RefreshToken", refreshAccessTokenRequest.RefreshTokent, connectionId); + //if (!tokenTextExisting) + //{ + // return StatusCode(401, new { message = "Invalid to retrieve token through refreshToken" }); // message may be omitted in prod build, to avoid exposing implementation details. + //} + + //return await tokenHelper.GenerateJwtToken(user, username, connectionId); //the old refresh token is removed } - var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); - var newLoginConnectionId = Guid.NewGuid(); - return await tokenHelper.GenerateJwtToken(user, model.Username, newLoginConnectionId); + throw new NotSupportedException(); } + /// /// Generate new JWT token according to refresh token and connectionId. /// This call supports AllowAnonymous. So after the access token expires, the client may still acquire new one without login again. diff --git a/Core3WebApi/Core3WebApi.csproj b/Core3WebApi/Core3WebApi.csproj index 02eb2ba..a4f9a16 100644 --- a/Core3WebApi/Core3WebApi.csproj +++ b/Core3WebApi/Core3WebApi.csproj @@ -14,7 +14,6 @@ - diff --git a/Core3WebApi/Helpers/ValidateModelAttribute.cs b/Core3WebApi/Helpers/ValidateModelAttribute.cs deleted file mode 100644 index 50d6914..0000000 --- a/Core3WebApi/Helpers/ValidateModelAttribute.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.AspNetCore.Mvc.Filters; -using Microsoft.AspNetCore.Mvc; -using System.Net; - -namespace WebApp.Utilities -{ - public class ValidateModelAttribute : ActionFilterAttribute - { - public override void OnActionExecuting(ActionExecutingContext context) - { - if (!context.ModelState.IsValid) - { - context.Result = new BadRequestObjectResult(context.ModelState); - } - } - } -} diff --git a/Core3WebApi/Program.cs b/Core3WebApi/Program.cs index 8fe22f3..35c1ecc 100644 --- a/Core3WebApi/Program.cs +++ b/Core3WebApi/Program.cs @@ -14,6 +14,7 @@ using Microsoft.Extensions.Logging; using System; using System.IO; +using WebApp.Utilities; System.Reflection.Assembly appAssembly = System.Reflection.Assembly.GetExecutingAssembly(); string dirOfAppAssembly = System.IO.Path.GetDirectoryName(appAssembly.Location); @@ -69,15 +70,15 @@ builder.Services.AddControllers(configure => { #if DEBUG - configure.Conventions.Add(new Fonlow.CodeDom.Web.ApiExplorerVisibilityEnabledConvention());//To make ApiExplorer be visible to WebApiClientGen + configure.Conventions.Add(new Fonlow.CodeDom.Web.ApiExplorerVisibilityEnabledConvention());//To make ApiExplorer be visible to WebApiClientGen #endif - configure.Filters.Add(new WebApp.Utilities.ValidateModelAttribute()); - -}).AddNewtonsoftJson(options => + configure.ModelBinderProviders.Insert(0, new OAuth2RequestBinderProvider()); +}) +.AddJsonOptions(// as of .NET 7/8, could not handle JS/CS test cases getInt2D, postInt2D and PostDictionaryOfPeople, around 14 C# test cases fail. +options => { - options.SerializerSettings.Converters.Add(new DateOnlyJsonConverter()); - options.SerializerSettings.Converters.Add(new DateOnlyNullableJsonConverter()); - options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; + + }); builder.Services.AddAuthentication( diff --git a/Core3WebApi/Properties/launchSettings.json b/Core3WebApi/Properties/launchSettings.json index 3a4234c..ee96a38 100644 --- a/Core3WebApi/Properties/launchSettings.json +++ b/Core3WebApi/Properties/launchSettings.json @@ -19,8 +19,6 @@ }, "Core3WebApi": { "commandName": "Project", - "launchBrowser": true, - "launchUrl": "weatherforecast", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" diff --git a/CoreWebApi.ClientApi/WebApiClientAuto.cs b/CoreWebApi.ClientApi/WebApiClientAuto.cs index b1787e7..440b305 100644 --- a/CoreWebApi.ClientApi/WebApiClientAuto.cs +++ b/CoreWebApi.ClientApi/WebApiClientAuto.cs @@ -16,31 +16,28 @@ namespace DemoWebApi.Controllers.Client using System.Net.Http; using Newtonsoft.Json; using Fonlow.Net.Http; - - - /// - /// Complex hero type - /// + + public class Hero : object { - + public long Id { get; set; } - + public string Name { get; set; } } - + /// /// Manage user accounts stored in ASP.NET Core Identity database. /// Authorize: Bearer /// public partial class Account { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public Account(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public Account(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -51,38 +48,38 @@ public Account(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSer this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// POST api/Account/AddRole?userId={userId}&roleName={roleName} /// public async Task AddRoleAsync(System.Guid userId, string roleName, Action handleHeaders = null) { - var requestUri = "api/Account/AddRole?userId=" + userId + "&roleName=" + (roleName == null ? "" : Uri.EscapeDataString(roleName)); + var requestUri = "api/Account/AddRole?userId="+userId+"&roleName="+(roleName == null ? "" : Uri.EscapeDataString(roleName)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = await client.SendAsync(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/Account/AddRole?userId={userId}&roleName={roleName} /// public System.Net.Http.HttpResponseMessage AddRole(System.Guid userId, string roleName, Action handleHeaders = null) { - var requestUri = "api/Account/AddRole?userId=" + userId + "&roleName=" + (roleName == null ? "" : Uri.EscapeDataString(roleName)); + var requestUri = "api/Account/AddRole?userId="+userId+"&roleName="+(roleName == null ? "" : Uri.EscapeDataString(roleName)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = client.Send(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// DELETE api/Account/AdminRemoveUserRefreshTokens/{username} /// Authorize: Roles: admin; /// public async Task AdminRemoverRefreshTokensOfUsersAsync(string username, Action handleHeaders = null) { - var requestUri = "api/Account/AdminRemoveUserRefreshTokens/" + (username == null ? "" : Uri.EscapeDataString(username)); + var requestUri = "api/Account/AdminRemoveUserRefreshTokens/"+(username == null ? "" : Uri.EscapeDataString(username)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -98,14 +95,14 @@ public async Task AdminRemoverRefreshTokensOfUsersAsync(string username, Ac responseMessage.Dispose(); } } - + /// /// DELETE api/Account/AdminRemoveUserRefreshTokens/{username} /// Authorize: Roles: admin; /// public int AdminRemoverRefreshTokensOfUsers(string username, Action handleHeaders = null) { - var requestUri = "api/Account/AdminRemoveUserRefreshTokens/" + (username == null ? "" : Uri.EscapeDataString(username)); + var requestUri = "api/Account/AdminRemoveUserRefreshTokens/"+(username == null ? "" : Uri.EscapeDataString(username)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -121,7 +118,7 @@ public int AdminRemoverRefreshTokensOfUsers(string username, Action /// PUT api/Account/ChangePassword /// @@ -139,7 +136,7 @@ public int AdminRemoverRefreshTokensOfUsers(string username, Action /// PUT api/Account/ChangePassword /// @@ -157,7 +154,7 @@ public System.Net.Http.HttpResponseMessage ChangePassword(Fonlow.WebApp.Accounts responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// Just a demo, but revealing some basic ForgotPassword features: /// 1. If user not found, return NoContent @@ -178,7 +175,7 @@ public System.Net.Http.HttpResponseMessage ChangePassword(Fonlow.WebApp.Accounts responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// Just a demo, but revealing some basic ForgotPassword features: /// 1. If user not found, return NoContent @@ -199,7 +196,7 @@ public System.Net.Http.HttpResponseMessage ForgotPassword(string email, Action /// GET api/Account/AllRoleNames /// @@ -223,7 +220,7 @@ public async Task GetAllRoleNamesAsync(Action /// GET api/Account/AllRoleNames /// @@ -247,13 +244,13 @@ public string[] GetAllRoleNames(Action /// GET api/Account/idByEmail?email={email} /// public async Task GetUserIdByEmailAsync(string email, Action handleHeaders = null) { - var requestUri = "api/Account/idByEmail?email=" + (email == null ? "" : Uri.EscapeDataString(email)); + var requestUri = "api/Account/idByEmail?email="+(email == null ? "" : Uri.EscapeDataString(email)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -270,13 +267,13 @@ public string[] GetAllRoleNames(Action /// GET api/Account/idByEmail?email={email} /// public System.Guid GetUserIdByEmail(string email, Action handleHeaders = null) { - var requestUri = "api/Account/idByEmail?email=" + (email == null ? "" : Uri.EscapeDataString(email)); + var requestUri = "api/Account/idByEmail?email="+(email == null ? "" : Uri.EscapeDataString(email)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -293,13 +290,13 @@ public System.Guid GetUserIdByEmail(string email, Action /// GET api/Account/idByFullName?cn={cn} /// public async Task GetUserIdByFullNameAsync(string cn, Action handleHeaders = null) { - var requestUri = "api/Account/idByFullName?cn=" + (cn == null ? "" : Uri.EscapeDataString(cn)); + var requestUri = "api/Account/idByFullName?cn="+(cn == null ? "" : Uri.EscapeDataString(cn)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -316,13 +313,13 @@ public System.Guid GetUserIdByEmail(string email, Action /// GET api/Account/idByFullName?cn={cn} /// public System.Guid GetUserIdByFullName(string cn, Action handleHeaders = null) { - var requestUri = "api/Account/idByFullName?cn=" + (cn == null ? "" : Uri.EscapeDataString(cn)); + var requestUri = "api/Account/idByFullName?cn="+(cn == null ? "" : Uri.EscapeDataString(cn)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -339,13 +336,13 @@ public System.Guid GetUserIdByFullName(string cn, Action /// GET api/Account/UserIdByUser?username={username} /// public async Task GetUserIdByUserAsync(string username, Action handleHeaders = null) { - var requestUri = "api/Account/UserIdByUser?username=" + (username == null ? "" : Uri.EscapeDataString(username)); + var requestUri = "api/Account/UserIdByUser?username="+(username == null ? "" : Uri.EscapeDataString(username)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -362,13 +359,13 @@ public System.Guid GetUserIdByFullName(string cn, Action /// GET api/Account/UserIdByUser?username={username} /// public System.Guid GetUserIdByUser(string username, Action handleHeaders = null) { - var requestUri = "api/Account/UserIdByUser?username=" + (username == null ? "" : Uri.EscapeDataString(username)); + var requestUri = "api/Account/UserIdByUser?username="+(username == null ? "" : Uri.EscapeDataString(username)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -385,7 +382,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Mapping between email address and user Id /// GET api/Account/UserIdMapByEmail @@ -411,7 +408,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Mapping between email address and user Id /// GET api/Account/UserIdMapByEmail @@ -437,7 +434,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Mapping between full user name and user Id /// GET api/Account/UserIdMapByFullName @@ -463,7 +460,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Mapping between full user name and user Id /// GET api/Account/UserIdMapByFullName @@ -489,7 +486,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Get user info of current logged user /// GET api/Account/UserInfo @@ -514,7 +511,7 @@ public System.Guid GetUserIdByUser(string username, Action /// Get user info of current logged user /// GET api/Account/UserInfo @@ -539,7 +536,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action /// : InternalRoles /// GET api/Account/UserInfoById?id={id} @@ -547,7 +544,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action public async Task GetUserInfoAsync(System.Guid id, Action handleHeaders = null) { - var requestUri = "api/Account/UserInfoById?id=" + id; + var requestUri = "api/Account/UserInfoById?id="+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -565,7 +562,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action /// : InternalRoles /// GET api/Account/UserInfoById?id={id} @@ -573,7 +570,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(System.Guid id, Action handleHeaders = null) { - var requestUri = "api/Account/UserInfoById?id=" + id; + var requestUri = "api/Account/UserInfoById?id="+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -591,31 +588,31 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(System.Guid i responseMessage.Dispose(); } } - + /// /// POST api/Account/Logout/{connectionId} /// public async Task LogoutAsync(System.Guid connectionId, Action handleHeaders = null) { - var requestUri = "api/Account/Logout/" + connectionId; + var requestUri = "api/Account/Logout/"+connectionId; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = await client.SendAsync(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/Account/Logout/{connectionId} /// public System.Net.Http.HttpResponseMessage Logout(System.Guid connectionId, Action handleHeaders = null) { - var requestUri = "api/Account/Logout/" + connectionId; + var requestUri = "api/Account/Logout/"+connectionId; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = client.Send(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// Create user, but without role /// POST api/Account/Register @@ -645,7 +642,7 @@ public System.Net.Http.HttpResponseMessage Logout(System.Guid connectionId, Acti responseMessage.Dispose(); } } - + /// /// Create user, but without role /// POST api/Account/Register @@ -675,7 +672,7 @@ public System.Guid Register(Fonlow.WebApp.Accounts.Client.RegisterBindingModel m responseMessage.Dispose(); } } - + /// /// Admin or scheduler clean up old user tokens /// DELETE api/Account/RemoveOldUserTokens/{pastDateUtc} @@ -683,7 +680,7 @@ public System.Guid Register(Fonlow.WebApp.Accounts.Client.RegisterBindingModel m /// public async Task RemoveOldUserTokensAsync(System.DateTime pastDateUtc, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveOldUserTokens/" + pastDateUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/Account/RemoveOldUserTokens/"+pastDateUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -699,7 +696,7 @@ public async Task RemoveOldUserTokensAsync(System.DateTime pastDateUtc, Act responseMessage.Dispose(); } } - + /// /// Admin or scheduler clean up old user tokens /// DELETE api/Account/RemoveOldUserTokens/{pastDateUtc} @@ -707,7 +704,7 @@ public async Task RemoveOldUserTokensAsync(System.DateTime pastDateUtc, Act /// public int RemoveOldUserTokens(System.DateTime pastDateUtc, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveOldUserTokens/" + pastDateUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/Account/RemoveOldUserTokens/"+pastDateUtc.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -723,7 +720,7 @@ public int RemoveOldUserTokens(System.DateTime pastDateUtc, Action /// User to remove all refresh tokens of user /// DELETE api/Account/RemoveRefreshTokensOfUser @@ -746,7 +743,7 @@ public async Task RemoveRefreshTokensOfUserAsync(Action /// User to remove all refresh tokens of user /// DELETE api/Account/RemoveRefreshTokensOfUser @@ -769,61 +766,61 @@ public int RemoveRefreshTokensOfUser(Action /// DELETE api/Account/RemoveRole?userId={userId}&roleName={roleName} /// public async Task RemoveRoleAsync(System.Guid userId, string roleName, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveRole?userId=" + userId + "&roleName=" + (roleName == null ? "" : Uri.EscapeDataString(roleName)); + var requestUri = "api/Account/RemoveRole?userId="+userId+"&roleName="+(roleName == null ? "" : Uri.EscapeDataString(roleName)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// DELETE api/Account/RemoveRole?userId={userId}&roleName={roleName} /// public System.Net.Http.HttpResponseMessage RemoveRole(System.Guid userId, string roleName, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveRole?userId=" + userId + "&roleName=" + (roleName == null ? "" : Uri.EscapeDataString(roleName)); + var requestUri = "api/Account/RemoveRole?userId="+userId+"&roleName="+(roleName == null ? "" : Uri.EscapeDataString(roleName)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// Remove user and also remove from the entities table. /// DELETE api/Account/RemoveUser?userId={userId} /// public async Task RemoveUserAsync(System.Guid userId, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveUser?userId=" + userId; + var requestUri = "api/Account/RemoveUser?userId="+userId; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// Remove user and also remove from the entities table. /// DELETE api/Account/RemoveUser?userId={userId} /// public System.Net.Http.HttpResponseMessage RemoveUser(System.Guid userId, Action handleHeaders = null) { - var requestUri = "api/Account/RemoveUser?userId=" + userId; + var requestUri = "api/Account/RemoveUser?userId="+userId; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/Account/ResetPassword /// @@ -841,7 +838,7 @@ public System.Net.Http.HttpResponseMessage RemoveUser(System.Guid userId, Action responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/Account/ResetPassword /// @@ -859,7 +856,7 @@ public System.Net.Http.HttpResponseMessage ResetPassword(Fonlow.WebApp.Accounts. responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// PUT api/Account/SetPassword /// @@ -877,7 +874,7 @@ public System.Net.Http.HttpResponseMessage ResetPassword(Fonlow.WebApp.Accounts. responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// PUT api/Account/SetPassword /// @@ -895,7 +892,7 @@ public System.Net.Http.HttpResponseMessage SetPassword(Fonlow.WebApp.Accounts.Cl responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// : AdminOrManager /// PUT api/Account/SetUserPassword @@ -915,7 +912,7 @@ public System.Net.Http.HttpResponseMessage SetPassword(Fonlow.WebApp.Accounts.Cl responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// : AdminOrManager /// PUT api/Account/SetUserPassword @@ -936,19 +933,19 @@ public System.Net.Http.HttpResponseMessage SetUserPassword(Fonlow.WebApp.Account return responseMessage; } } - + /// /// For testing different commbinations of parameters and returns /// Authorize: Bearer /// public partial class DateTypes { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -959,7 +956,7 @@ public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonS this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// GET api/DateTypes/GetDateOnly /// @@ -982,7 +979,7 @@ public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonS responseMessage.Dispose(); } } - + /// /// GET api/DateTypes/GetDateOnly /// @@ -1005,13 +1002,13 @@ public System.DateOnly GetDateOnly(Action /// GET api/DateTypes/NullableDatetime/{hasValue} /// public async Task> GetDateTimeAsync(bool hasValue, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NullableDatetime/" + hasValue; + var requestUri = "api/DateTypes/NullableDatetime/"+hasValue; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1029,13 +1026,13 @@ public System.DateOnly GetDateOnly(Action /// GET api/DateTypes/NullableDatetime/{hasValue} /// public System.Nullable GetDateTime(bool hasValue, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NullableDatetime/" + hasValue; + var requestUri = "api/DateTypes/NullableDatetime/"+hasValue; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1053,7 +1050,7 @@ public System.DateOnly GetDateOnly(Action /// return DateTimeOffset.Now /// GET api/DateTypes/GetDateTimeOffset @@ -1077,7 +1074,7 @@ public System.DateOnly GetDateOnly(Action /// return DateTimeOffset.Now /// GET api/DateTypes/GetDateTimeOffset @@ -1101,13 +1098,13 @@ public System.DateTimeOffset GetDateTimeOffset(Action /// GET api/DateTypes/NextHour/{dt} /// public async Task GetNextHourAsync(System.DateTimeOffset dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextHour/" + dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/NextHour/"+dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1124,13 +1121,13 @@ public System.DateTimeOffset GetDateTimeOffset(Action /// GET api/DateTypes/NextHour/{dt} /// public System.DateTimeOffset GetNextHour(System.DateTimeOffset dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextHour/" + dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/NextHour/"+dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1147,14 +1144,14 @@ public System.DateTimeOffset GetNextHour(System.DateTimeOffset dt, Action /// If Dt is not defined, add a hour from now /// GET api/DateTypes/NextHourNullable?n={n}&dt={dt} /// public async Task GetNextHourNullableAsync(int n, System.Nullable dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextHourNullable?n=" + n + (dt.HasValue ? "&dt=" + dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/NextHourNullable?n="+n+(dt.HasValue?"&dt="+dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1171,14 +1168,14 @@ public System.DateTimeOffset GetNextHour(System.DateTimeOffset dt, Action /// If Dt is not defined, add a hour from now /// GET api/DateTypes/NextHourNullable?n={n}&dt={dt} /// public System.DateTimeOffset GetNextHourNullable(int n, System.Nullable dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextHourNullable?n=" + n + (dt.HasValue ? "&dt=" + dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/NextHourNullable?n="+n+(dt.HasValue?"&dt="+dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1195,13 +1192,13 @@ public System.DateTimeOffset GetNextHourNullable(int n, System.Nullable /// GET api/DateTypes/NextYear/{dt} /// public async Task GetNextYearAsync(System.DateTime dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextYear/" + dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/NextYear/"+dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1218,13 +1215,13 @@ public System.DateTimeOffset GetNextHourNullable(int n, System.Nullable /// GET api/DateTypes/NextYear/{dt} /// public System.DateTime GetNextYear(System.DateTime dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextYear/" + dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/NextYear/"+dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1241,14 +1238,14 @@ public System.DateTime GetNextYear(System.DateTime dt, Action /// If Dt is not defined, add a year from now /// GET api/DateTypes/NextYearNullable?n={n}&dt={dt} /// public async Task GetNextYearNullableAsync(int n, System.Nullable dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextYearNullable?n=" + n + (dt.HasValue ? "&dt=" + dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/NextYearNullable?n="+n+(dt.HasValue?"&dt="+dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1265,14 +1262,14 @@ public System.DateTime GetNextYear(System.DateTime dt, Action /// If Dt is not defined, add a year from now /// GET api/DateTypes/NextYearNullable?n={n}&dt={dt} /// public System.DateTime GetNextYearNullable(int n, System.Nullable dt, Action handleHeaders = null) { - var requestUri = "api/DateTypes/NextYearNullable?n=" + n + (dt.HasValue ? "&dt=" + dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/NextYearNullable?n="+n+(dt.HasValue?"&dt="+dt.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1289,7 +1286,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// Client should send DateTime.Date /// POST api/DateTypes/IsDateTimeDate @@ -1319,7 +1316,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// Client should send DateTime.Date /// POST api/DateTypes/IsDateTimeDate @@ -1349,7 +1346,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// POST api/DateTypes/IsDateTimeOffsetDate /// @@ -1378,7 +1375,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// POST api/DateTypes/IsDateTimeOffsetDate /// @@ -1407,7 +1404,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// POST api/DateTypes/ForDateOnly /// @@ -1435,7 +1432,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable /// POST api/DateTypes/ForDateOnly /// @@ -1463,7 +1460,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action /// POST api/DateTypes/DateOnlyNullable /// @@ -1492,7 +1489,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action /// POST api/DateTypes/DateOnlyNullable /// @@ -1521,7 +1518,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action /// POST api/DateTypes/ForDateTime /// @@ -1549,7 +1546,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action /// POST api/DateTypes/ForDateTime /// @@ -1577,7 +1574,7 @@ public System.DateTime PostDateTime(System.DateTime d, Action /// return d; /// POST api/DateTypes/ForDateTimeOffset @@ -1606,7 +1603,7 @@ public System.DateTime PostDateTime(System.DateTime d, Action /// return d; /// POST api/DateTypes/ForDateTimeOffset @@ -1635,7 +1632,7 @@ public System.DateTimeOffset PostDateTimeOffset(System.DateTimeOffset d, Action< responseMessage.Dispose(); } } - + /// /// return d.ToString("O") /// POST api/DateTypes/ForDateTimeOffsetForO @@ -1657,14 +1654,14 @@ public async Task PostDateTimeOffsetForOAsync(System.DateTimeOffset d, A if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// return d.ToString("O") /// POST api/DateTypes/ForDateTimeOffsetForO @@ -1686,14 +1683,14 @@ public string PostDateTimeOffsetForO(System.DateTimeOffset d, Action /// POST api/DateTypes/ForDateTimeOffsetForOffset /// @@ -1721,7 +1718,7 @@ public string PostDateTimeOffsetForO(System.DateTimeOffset d, Action /// POST api/DateTypes/ForDateTimeOffsetForOffset /// @@ -1749,7 +1746,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.Dispose(); } } - + /// /// Returned is DateTimeOffset? /// POST api/DateTypes/DateTimeOffsetNullable @@ -1779,7 +1776,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.Dispose(); } } - + /// /// Returned is DateTimeOffset? /// POST api/DateTypes/DateTimeOffsetNullable @@ -1809,7 +1806,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.Dispose(); } } - + /// /// POST api/DateTypes/ForDateTimeOffsetStringForOffset /// @@ -1837,7 +1834,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.Dispose(); } } - + /// /// POST api/DateTypes/ForDateTimeOffsetStringForOffset /// @@ -1865,7 +1862,7 @@ public System.TimeSpan PostDateTimeOffsetStringForOffset(string s, Action /// POST api/DateTypes/NextYear /// @@ -1893,7 +1890,7 @@ public System.TimeSpan PostDateTimeOffsetStringForOffset(string s, Action /// POST api/DateTypes/NextYear /// @@ -1921,13 +1918,13 @@ public System.DateTime PostNextYear(System.DateTime dt, Action /// GET api/DateTypes/DateOnlyStringQuery?d={d} /// public async Task QueryDateOnlyAsStringAsync(string d, Action handleHeaders = null) { - var requestUri = "api/DateTypes/DateOnlyStringQuery?d=" + (d == null ? "" : Uri.EscapeDataString(d)); + var requestUri = "api/DateTypes/DateOnlyStringQuery?d="+(d == null ? "" : Uri.EscapeDataString(d)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1944,13 +1941,13 @@ public System.DateTime PostNextYear(System.DateTime dt, Action /// GET api/DateTypes/DateOnlyStringQuery?d={d} /// public System.DateOnly QueryDateOnlyAsString(string d, Action handleHeaders = null) { - var requestUri = "api/DateTypes/DateOnlyStringQuery?d=" + (d == null ? "" : Uri.EscapeDataString(d)); + var requestUri = "api/DateTypes/DateOnlyStringQuery?d="+(d == null ? "" : Uri.EscapeDataString(d)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1967,13 +1964,13 @@ public System.DateOnly QueryDateOnlyAsString(string d, Action /// GET api/DateTypes/RouteDateTimeOffset/{d} /// public async Task RouteDateTimeOffsetAsync(System.DateTimeOffset d, Action handleHeaders = null) { - var requestUri = "api/DateTypes/RouteDateTimeOffset/" + d.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/RouteDateTimeOffset/"+d.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1990,13 +1987,13 @@ public System.DateOnly QueryDateOnlyAsString(string d, Action /// GET api/DateTypes/RouteDateTimeOffset/{d} /// public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action handleHeaders = null) { - var requestUri = "api/DateTypes/RouteDateTimeOffset/" + d.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); + var requestUri = "api/DateTypes/RouteDateTimeOffset/"+d.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2013,7 +2010,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action responseMessage.Dispose(); } } - + /// /// Return Tuple DateTime?, DateTime? /// GET api/DateTypes/SearchDateRange?startDate={startDate}&endDate={endDate} @@ -2022,7 +2019,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action /// DateTime? endDate = null public async Task, System.Nullable>> SearchDateRangeAsync(System.Nullable startDate, System.Nullable endDate, Action handleHeaders = null) { - var requestUri = "api/DateTypes/SearchDateRange?" + (startDate.HasValue ? "startDate=" + startDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty) + (endDate.HasValue ? "&endDate=" + endDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/SearchDateRange?"+(startDate.HasValue?"startDate="+startDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty)+(endDate.HasValue?"&endDate="+endDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2040,7 +2037,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action responseMessage.Dispose(); } } - + /// /// Return Tuple DateTime?, DateTime? /// GET api/DateTypes/SearchDateRange?startDate={startDate}&endDate={endDate} @@ -2049,7 +2046,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action /// DateTime? endDate = null public System.Tuple, System.Nullable> SearchDateRange(System.Nullable startDate, System.Nullable endDate, Action handleHeaders = null) { - var requestUri = "api/DateTypes/SearchDateRange?" + (startDate.HasValue ? "startDate=" + startDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty) + (endDate.HasValue ? "&endDate=" + endDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ") : String.Empty); + var requestUri = "api/DateTypes/SearchDateRange?"+(startDate.HasValue?"startDate="+startDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty)+(endDate.HasValue?"&endDate="+endDate.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"):String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2068,18 +2065,18 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action } } } - + /// /// Authorize: Bearer /// public partial class Entities { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -2090,7 +2087,7 @@ public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSe this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// POST api/Entities/createCompany /// @@ -2119,7 +2116,7 @@ public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSe responseMessage.Dispose(); } } - + /// /// POST api/Entities/createCompany /// @@ -2148,7 +2145,7 @@ public DemoWebApi.DemoData.Client.Company CreateCompany(DemoWebApi.DemoData.Clie responseMessage.Dispose(); } } - + /// /// POST api/Entities/createPerson /// @@ -2175,7 +2172,7 @@ public async Task CreatePersonAsync(DemoWebApi.DemoData.Client.Person p, A responseMessage.Dispose(); } } - + /// /// POST api/Entities/createPerson /// @@ -2202,7 +2199,7 @@ public long CreatePerson(DemoWebApi.DemoData.Client.Person p, Action /// POST api/Entities/createPerson2 /// @@ -2231,7 +2228,7 @@ public long CreatePerson(DemoWebApi.DemoData.Client.Person p, Action /// POST api/Entities/createPerson2 /// @@ -2260,7 +2257,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien responseMessage.Dispose(); } } - + /// /// POST api/Entities/createPerson3 /// @@ -2289,7 +2286,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien responseMessage.Dispose(); } } - + /// /// POST api/Entities/createPerson3 /// @@ -2318,13 +2315,13 @@ public DemoWebApi.DemoData.Client.Person CreatePerson3(DemoWebApi.DemoData.Clien responseMessage.Dispose(); } } - + /// /// DELETE api/Entities/{id} /// public async Task DeleteAsync(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/" + id; + var requestUri = "api/Entities/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2337,13 +2334,13 @@ public async Task DeleteAsync(long id, Action /// DELETE api/Entities/{id} /// public void Delete(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/" + id; + var requestUri = "api/Entities/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2356,13 +2353,13 @@ public void Delete(long id, Action h responseMessage.Dispose(); } } - + /// /// GET api/Entities/Company/{id} /// public async Task GetCompanyAsync(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/Company/" + id; + var requestUri = "api/Entities/Company/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2380,13 +2377,13 @@ public void Delete(long id, Action h responseMessage.Dispose(); } } - + /// /// GET api/Entities/Company/{id} /// public DemoWebApi.DemoData.Client.Company GetCompany(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/Company/" + id; + var requestUri = "api/Entities/Company/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2404,7 +2401,7 @@ public DemoWebApi.DemoData.Client.Company GetCompany(long id, Action /// POST api/Entities/Mims /// @@ -2433,7 +2430,7 @@ public DemoWebApi.DemoData.Client.Company GetCompany(long id, Action /// POST api/Entities/Mims /// @@ -2462,7 +2459,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData responseMessage.Dispose(); } } - + /// /// POST api/Entities/MyGeneric /// @@ -2491,7 +2488,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData responseMessage.Dispose(); } } - + /// /// POST api/Entities/MyGeneric /// @@ -2520,7 +2517,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.Dispose(); } } - + /// /// POST api/Entities/MyGenericPerson /// @@ -2549,7 +2546,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.Dispose(); } } - + /// /// POST api/Entities/MyGenericPerson /// @@ -2578,7 +2575,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.Dispose(); } } - + /// /// Get a person /// so to know the person @@ -2588,7 +2585,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri /// person in db public async Task GetPersonAsync(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/getPerson/" + id; + var requestUri = "api/Entities/getPerson/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2606,7 +2603,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.Dispose(); } } - + /// /// Get a person /// so to know the person @@ -2616,7 +2613,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri /// person in db public DemoWebApi.DemoData.Client.Person GetPerson(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/getPerson/" + id; + var requestUri = "api/Entities/getPerson/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2634,13 +2631,13 @@ public DemoWebApi.DemoData.Client.Person GetPerson(long id, Action /// GET api/Entities/getPerson2/{id} /// public async Task GetPerson2Async(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/getPerson2/" + id; + var requestUri = "api/Entities/getPerson2/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2658,13 +2655,13 @@ public DemoWebApi.DemoData.Client.Person GetPerson(long id, Action /// GET api/Entities/getPerson2/{id} /// public DemoWebApi.DemoData.Client.Person GetPerson2(long id, Action handleHeaders = null) { - var requestUri = "api/Entities/getPerson2/" + id; + var requestUri = "api/Entities/getPerson2/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2682,13 +2679,13 @@ public DemoWebApi.DemoData.Client.Person GetPerson2(long id, Action /// PUT api/Entities/link?id={id}&relationship={relationship} /// public async Task LinkPersonAsync(long id, string relationship, DemoWebApi.DemoData.Client.Person person, Action handleHeaders = null) { - var requestUri = "api/Entities/link?id=" + id + "&relationship=" + (relationship == null ? "" : Uri.EscapeDataString(relationship)); + var requestUri = "api/Entities/link?id="+id+"&relationship="+(relationship == null ? "" : Uri.EscapeDataString(relationship)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -2709,13 +2706,13 @@ public async Task LinkPersonAsync(long id, string relationship, DemoWebApi responseMessage.Dispose(); } } - + /// /// PUT api/Entities/link?id={id}&relationship={relationship} /// public bool LinkPerson(long id, string relationship, DemoWebApi.DemoData.Client.Person person, Action handleHeaders = null) { - var requestUri = "api/Entities/link?id=" + id + "&relationship=" + (relationship == null ? "" : Uri.EscapeDataString(relationship)); + var requestUri = "api/Entities/link?id="+id+"&relationship="+(relationship == null ? "" : Uri.EscapeDataString(relationship)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -2736,7 +2733,7 @@ public bool LinkPerson(long id, string relationship, DemoWebApi.DemoData.Client. responseMessage.Dispose(); } } - + /// /// PATCH api/Entities/patchPerson /// @@ -2757,14 +2754,14 @@ public async Task PatchPersonAsync(DemoWebApi.DemoData.Client.Person per if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// PATCH api/Entities/patchPerson /// @@ -2785,14 +2782,14 @@ public string PatchPerson(DemoWebApi.DemoData.Client.Person person, Action /// POST api/Entities/IdMap /// @@ -2821,7 +2818,7 @@ public string PatchPerson(DemoWebApi.DemoData.Client.Person person, Action /// POST api/Entities/IdMap /// @@ -2850,7 +2847,7 @@ public DemoWebApi.DemoData.Client.IdMap PostIdMap(DemoWebApi.DemoData.Client.IdM responseMessage.Dispose(); } } - + /// /// PUT api/Entities/updatePerson /// @@ -2871,14 +2868,14 @@ public async Task UpdatePersonAsync(DemoWebApi.DemoData.Client.Person pe if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// PUT api/Entities/updatePerson /// @@ -2899,7 +2896,7 @@ public string UpdatePerson(DemoWebApi.DemoData.Client.Person person, Action /// Heroes operations /// Authorize: Bearer /// public partial class Heroes { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public Heroes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public Heroes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -2930,13 +2927,13 @@ public Heroes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSeri this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// DELETE api/Heroes/{id} /// public async Task DeleteAsync(long id, Action handleHeaders = null) { - var requestUri = "api/Heroes/" + id; + var requestUri = "api/Heroes/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2949,13 +2946,13 @@ public async Task DeleteAsync(long id, Action /// DELETE api/Heroes/{id} /// public void Delete(long id, Action handleHeaders = null) { - var requestUri = "api/Heroes/" + id; + var requestUri = "api/Heroes/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2968,7 +2965,7 @@ public void Delete(long id, Action h responseMessage.Dispose(); } } - + /// /// GET api/Heroes/asyncHeroes /// @@ -2991,7 +2988,7 @@ public void Delete(long id, Action h responseMessage.Dispose(); } } - + /// /// GET api/Heroes/asyncHeroes /// @@ -3014,14 +3011,14 @@ public DemoWebApi.Controllers.Client.Hero[] GetAsyncHeroes(Action /// Get a hero. /// GET api/Heroes/{id} /// public async Task GetHeroAsync(long id, Action handleHeaders = null) { - var requestUri = "api/Heroes/" + id; + var requestUri = "api/Heroes/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3039,14 +3036,14 @@ public DemoWebApi.Controllers.Client.Hero[] GetAsyncHeroes(Action /// Get a hero. /// GET api/Heroes/{id} /// public DemoWebApi.Controllers.Client.Hero GetHero(long id, Action handleHeaders = null) { - var requestUri = "api/Heroes/" + id; + var requestUri = "api/Heroes/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3064,7 +3061,7 @@ public DemoWebApi.Controllers.Client.Hero GetHero(long id, Action /// Get all heroes. /// GET api/Heroes @@ -3089,7 +3086,7 @@ public DemoWebApi.Controllers.Client.Hero GetHero(long id, Action /// Get all heroes. /// GET api/Heroes @@ -3114,7 +3111,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetHeros(Action /// POST api/Heroes /// @@ -3143,7 +3140,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetHeros(Action /// POST api/Heroes /// @@ -3172,14 +3169,14 @@ public DemoWebApi.Controllers.Client.Hero Post(string name, Action /// Add a hero /// POST api/Heroes/q?name={name} /// public async Task PostWithQueryAsync(string name, Action handleHeaders = null) { - var requestUri = "api/Heroes/q?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Heroes/q?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = await client.SendAsync(httpRequestMessage); try @@ -3196,14 +3193,14 @@ public DemoWebApi.Controllers.Client.Hero Post(string name, Action /// Add a hero /// POST api/Heroes/q?name={name} /// public DemoWebApi.Controllers.Client.Hero PostWithQuery(string name, Action handleHeaders = null) { - var requestUri = "api/Heroes/q?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Heroes/q?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var responseMessage = client.Send(httpRequestMessage); try @@ -3220,7 +3217,7 @@ public DemoWebApi.Controllers.Client.Hero PostWithQuery(string name, Action /// Update hero. /// PUT api/Heroes @@ -3250,7 +3247,7 @@ public DemoWebApi.Controllers.Client.Hero PostWithQuery(string name, Action /// Update hero. /// PUT api/Heroes @@ -3280,7 +3277,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero responseMessage.Dispose(); } } - + /// /// Search heroes /// GET api/Heroes/search/{name} @@ -3289,7 +3286,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero /// Hero array matching the keyword. public async Task SearchAsync(string name, Action handleHeaders = null) { - var requestUri = "api/Heroes/search/" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Heroes/search/"+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3307,7 +3304,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero responseMessage.Dispose(); } } - + /// /// Search heroes /// GET api/Heroes/search/{name} @@ -3316,7 +3313,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero /// Hero array matching the keyword. public DemoWebApi.Controllers.Client.Hero[] Search(string name, Action handleHeaders = null) { - var requestUri = "api/Heroes/search/" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Heroes/search/"+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3335,15 +3332,15 @@ public DemoWebApi.Controllers.Client.Hero[] Search(string name, Action /// GET api/Home /// @@ -3367,7 +3364,7 @@ public Home(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerial responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// GET api/Home /// @@ -3381,19 +3378,97 @@ public System.Net.Http.HttpResponseMessage Index(Action + /// POST api/Polymorphism + /// + public async Task AuthenticateAsync(Fonlow.AspNetCore.OAuth2.Client.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + using var requestWriter = new System.IO.StringWriter(); + var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); + requestSerializer.Serialize(requestWriter, model); + var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); + var serializer = JsonSerializer.Create(jsonSerializerSettings); + return serializer.Deserialize(jsonReader); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism + /// + public Fonlow.AspNetCore.OAuth2.Client.RequestBase Authenticate(Fonlow.AspNetCore.OAuth2.Client.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + using var requestWriter = new System.IO.StringWriter(); + var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); + requestSerializer.Serialize(requestWriter, model); + var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = client.Send(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = responseMessage.Content.ReadAsStream(); + using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); + var serializer = JsonSerializer.Create(jsonSerializerSettings); + return serializer.Deserialize(jsonReader); + } + finally + { + responseMessage.Dispose(); + } + } + } + /// /// For testing different commbinations of parameters and returns /// Authorize: Bearer /// public partial class SuperDemo { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public SuperDemo(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public SuperDemo(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -3404,13 +3479,13 @@ public SuperDemo(System.Net.Http.HttpClient client, JsonSerializerSettings jsonS this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// GET api/SuperDemo/AthletheSearch?take={take}&skip={skip}&order={order}&sort={sort}&search={search} /// public async Task AthletheSearchAsync(System.Nullable take, int skip, string order, string sort, string search, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/AthletheSearch?" + (take.HasValue ? "take=" + take.Value.ToString() : String.Empty) + "&skip=" + skip + "&order=" + (order == null ? "" : Uri.EscapeDataString(order)) + "&sort=" + (sort == null ? "" : Uri.EscapeDataString(sort)) + "&search=" + (search == null ? "" : Uri.EscapeDataString(search)); + var requestUri = "api/SuperDemo/AthletheSearch?"+(take.HasValue?"take="+take.Value.ToString():String.Empty)+"&skip="+skip+"&order="+(order == null ? "" : Uri.EscapeDataString(order))+"&sort="+(sort == null ? "" : Uri.EscapeDataString(sort))+"&search="+(search == null ? "" : Uri.EscapeDataString(search)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3420,20 +3495,20 @@ public async Task AthletheSearchAsync(System.Nullable take, int ski if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/AthletheSearch?take={take}&skip={skip}&order={order}&sort={sort}&search={search} /// public string AthletheSearch(System.Nullable take, int skip, string order, string sort, string search, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/AthletheSearch?" + (take.HasValue ? "take=" + take.Value.ToString() : String.Empty) + "&skip=" + skip + "&order=" + (order == null ? "" : Uri.EscapeDataString(order)) + "&sort=" + (sort == null ? "" : Uri.EscapeDataString(sort)) + "&search=" + (search == null ? "" : Uri.EscapeDataString(search)); + var requestUri = "api/SuperDemo/AthletheSearch?"+(take.HasValue?"take="+take.Value.ToString():String.Empty)+"&skip="+skip+"&order="+(order == null ? "" : Uri.EscapeDataString(order))+"&sort="+(sort == null ? "" : Uri.EscapeDataString(sort))+"&search="+(search == null ? "" : Uri.EscapeDataString(search)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3443,14 +3518,14 @@ public string AthletheSearch(System.Nullable take, int skip, string order, if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ActionResult /// @@ -3463,7 +3538,7 @@ public string AthletheSearch(System.Nullable take, int skip, string order, responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// GET api/SuperDemo/ActionResult /// @@ -3476,7 +3551,7 @@ public System.Net.Http.HttpResponseMessage GetActionResult(Action /// GET api/SuperDemo/ActionResult2 /// @@ -3489,7 +3564,7 @@ public System.Net.Http.HttpResponseMessage GetActionResult(Action /// GET api/SuperDemo/ActionResult2 /// @@ -3502,7 +3577,7 @@ public System.Net.Http.HttpResponseMessage GetActionResult2(Action /// GET api/SuperDemo/ActionStringResult /// Status Codes: 200:OK : System.String @@ -3519,14 +3594,14 @@ public async Task GetActionStringResultAsync(Action /// GET api/SuperDemo/ActionStringResult /// Status Codes: 200:OK : System.String @@ -3543,14 +3618,14 @@ public string GetActionStringResult(Action /// GET api/SuperDemo/bool /// @@ -3572,7 +3647,7 @@ public async Task GetBoolAsync(Action /// GET api/SuperDemo/bool /// @@ -3594,7 +3669,7 @@ public bool GetBool(Action handleHea responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/byte /// @@ -3616,7 +3691,7 @@ public async Task GetbyteAsync(Action /// GET api/SuperDemo/byte /// @@ -3638,7 +3713,7 @@ public byte Getbyte(Action handleHea responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ByteArray /// @@ -3662,7 +3737,7 @@ public async Task GetByteArrayAsync(Action /// GET api/SuperDemo/ByteArray /// @@ -3686,7 +3761,7 @@ public byte[] GetByteArray(Action ha responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/char /// @@ -3709,7 +3784,7 @@ public async Task GetCharAsync(Action /// GET api/SuperDemo/char /// @@ -3732,7 +3807,7 @@ public char GetChar(Action handleHea responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/Collection /// @@ -3756,7 +3831,7 @@ public char GetChar(Action handleHea responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/Collection /// @@ -3780,13 +3855,13 @@ public DemoWebApi.DemoData.Client.Person[] GetCollection(Action /// GET api/SuperDemo/enumGet?d={d} /// public async Task GetDayAsync(DemoWebApi.DemoData.Client.Days d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumGet?d=" + d; + var requestUri = "api/SuperDemo/enumGet?d="+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3803,13 +3878,13 @@ public DemoWebApi.DemoData.Client.Person[] GetCollection(Action /// GET api/SuperDemo/enumGet?d={d} /// public DemoWebApi.DemoData.Client.Days GetDay(DemoWebApi.DemoData.Client.Days d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumGet?d=" + d; + var requestUri = "api/SuperDemo/enumGet?d="+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3826,7 +3901,7 @@ public DemoWebApi.DemoData.Client.Days GetDay(DemoWebApi.DemoData.Client.Days d, responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/decimal /// @@ -3849,7 +3924,7 @@ public async Task GetDecimalAsync(Action /// GET api/SuperDemo/decimal /// @@ -3872,13 +3947,13 @@ public decimal GetDecimal(Action han responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/decimalArrayQ?a={a} /// public async Task GetDecimalArrayQAsync(decimal[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/decimalArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/decimalArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3896,13 +3971,13 @@ public async Task GetDecimalArrayQAsync(decimal[] a, Action /// GET api/SuperDemo/decimalArrayQ?a={a} /// public decimal[] GetDecimalArrayQ(decimal[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/decimalArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/decimalArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3920,13 +3995,13 @@ public decimal[] GetDecimalArrayQ(decimal[] a, Action /// GET api/SuperDemo/decimal/{d} /// public async Task GetDecimalSquareAsync(decimal d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/decimal/" + d; + var requestUri = "api/SuperDemo/decimal/"+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3943,13 +4018,13 @@ public async Task GetDecimalSquareAsync(decimal d, Action /// GET api/SuperDemo/decimal/{d} /// public decimal GetDecimalSquare(decimal d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/decimal/" + d; + var requestUri = "api/SuperDemo/decimal/"+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3966,7 +4041,7 @@ public decimal GetDecimalSquare(decimal d, Action /// GET api/SuperDemo/DecimalZero /// @@ -3989,7 +4064,7 @@ public async Task GetDecimalZeroAsync(Action /// GET api/SuperDemo/DecimalZero /// @@ -4012,7 +4087,7 @@ public decimal GetDecimalZero(Action responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/StringStringDic /// @@ -4035,7 +4110,7 @@ public decimal GetDecimalZero(Action responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/StringStringDic /// @@ -4058,7 +4133,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/StringPersonDic /// @@ -4081,7 +4156,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/StringPersonDic /// @@ -4104,7 +4179,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/doulbe /// @@ -4126,7 +4201,7 @@ public async Task GetdoubleAsync(Action /// GET api/SuperDemo/doulbe /// @@ -4148,7 +4223,7 @@ public double Getdouble(Action handl responseMessage.Dispose(); } } - + /// /// Result of 0.1d + 0.2d - 0.3d /// GET api/SuperDemo/DoubleZero @@ -4171,7 +4246,7 @@ public async Task GetDoubleZeroAsync(Action /// Result of 0.1d + 0.2d - 0.3d /// GET api/SuperDemo/DoubleZero @@ -4194,7 +4269,7 @@ public double GetDoubleZero(Action h responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/EmptyString /// @@ -4210,14 +4285,14 @@ public async Task GetEmptyStringAsync(Action /// GET api/SuperDemo/EmptyString /// @@ -4233,20 +4308,20 @@ public string GetEmptyString(Action if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/enumArrayDays?a={a} /// public async Task GetEnumArrayDaysAsync(DemoWebApi.DemoData.Client.Days[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumArrayDays?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/enumArrayDays?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4264,13 +4339,13 @@ public string GetEmptyString(Action responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/enumArrayDays?a={a} /// public DemoWebApi.DemoData.Client.Days[] GetEnumArrayDays(DemoWebApi.DemoData.Client.Days[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumArrayDays?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/enumArrayDays?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4288,13 +4363,13 @@ public DemoWebApi.DemoData.Client.Days[] GetEnumArrayDays(DemoWebApi.DemoData.Cl responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/enumArrayQ2?a={a} /// public async Task GetEnumArrayQ2Async(System.DayOfWeek[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/enumArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4312,13 +4387,13 @@ public DemoWebApi.DemoData.Client.Days[] GetEnumArrayDays(DemoWebApi.DemoData.Cl responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/enumArrayQ2?a={a} /// public System.DayOfWeek[] GetEnumArrayQ2(System.DayOfWeek[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/enumArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4336,7 +4411,7 @@ public System.DayOfWeek[] GetEnumArrayQ2(System.DayOfWeek[] a, Action /// GET api/SuperDemo/FloatZero /// @@ -4358,7 +4433,7 @@ public async Task GetFloatZeroAsync(Action /// GET api/SuperDemo/FloatZero /// @@ -4380,7 +4455,7 @@ public float GetFloatZero(Action han responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ICollection /// @@ -4403,7 +4478,7 @@ public float GetFloatZero(Action han responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ICollection /// @@ -4426,7 +4501,7 @@ public DemoWebApi.DemoData.Client.Person[] GetICollection(Action /// GET api/SuperDemo/IList /// @@ -4449,7 +4524,7 @@ public DemoWebApi.DemoData.Client.Person[] GetICollection(Action /// GET api/SuperDemo/IList /// @@ -4472,7 +4547,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIList(Action /// GET api/SuperDemo/int2d /// @@ -4496,7 +4571,7 @@ public async Task GetInt2DAsync(Action /// GET api/SuperDemo/int2d /// @@ -4520,7 +4595,7 @@ public async Task GetInt2DAsync(Action /// GET api/SuperDemo/int2dJagged /// @@ -4544,7 +4619,7 @@ public async Task GetInt2DJaggedAsync(Action /// GET api/SuperDemo/int2dJagged /// @@ -4568,7 +4643,7 @@ public int[][] GetInt2DJagged(Action responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/intArray /// @@ -4592,7 +4667,7 @@ public async Task GetIntArrayAsync(Action /// GET api/SuperDemo/intArray /// @@ -4616,13 +4691,13 @@ public int[] GetIntArray(Action hand responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/intArrayQ?a={a} /// public async Task GetIntArrayQAsync(int[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/intArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/intArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4640,13 +4715,13 @@ public async Task GetIntArrayQAsync(int[] a, Action /// GET api/SuperDemo/intArrayQ?a={a} /// public int[] GetIntArrayQ(int[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/intArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/intArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4664,13 +4739,13 @@ public int[] GetIntArrayQ(int[] a, Action /// GET api/SuperDemo/intArrayQ2?a={a} /// public async Task GetIntArrayQ2Async(long[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/intArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/intArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4688,13 +4763,13 @@ public async Task GetIntArrayQ2Async(long[] a, Action /// GET api/SuperDemo/intArrayQ2?a={a} /// public long[] GetIntArrayQ2(long[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/intArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/intArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4712,13 +4787,13 @@ public long[] GetIntArrayQ2(long[] a, Action /// GET api/SuperDemo/int/{d} /// public async Task GetIntSquareAsync(int d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/int/" + d; + var requestUri = "api/SuperDemo/int/"+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4734,13 +4809,13 @@ public async Task GetIntSquareAsync(int d, Action /// GET api/SuperDemo/int/{d} /// public int GetIntSquare(int d, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/int/" + d; + var requestUri = "api/SuperDemo/int/"+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4756,7 +4831,7 @@ public int GetIntSquare(int d, Action /// GET api/SuperDemo/IReadOnlyCollection /// @@ -4779,7 +4854,7 @@ public int GetIntSquare(int d, Action /// GET api/SuperDemo/IReadOnlyCollection /// @@ -4802,7 +4877,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyCollection(Action /// GET api/SuperDemo/IReadOnlyList /// @@ -4825,7 +4900,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyCollection(Action /// GET api/SuperDemo/IReadOnlyList /// @@ -4848,7 +4923,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action /// GET api/SuperDemo/KeyValuePair /// @@ -4871,7 +4946,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action /// GET api/SuperDemo/KeyValuePair /// @@ -4894,7 +4969,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action /// GET api/SuperDemo/List /// @@ -4918,7 +4993,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action /// GET api/SuperDemo/List /// @@ -4942,13 +5017,13 @@ public DemoWebApi.DemoData.Client.Person[] GetList(Action /// GET api/SuperDemo/NullableDecimal/{hasValue} /// public async Task> GetNullableDecimalAsync(bool hasValue, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/NullableDecimal/" + hasValue; + var requestUri = "api/SuperDemo/NullableDecimal/"+hasValue; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -4966,13 +5041,13 @@ public DemoWebApi.DemoData.Client.Person[] GetList(Action /// GET api/SuperDemo/NullableDecimal/{hasValue} /// public System.Nullable GetNullableDecimal(bool hasValue, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/NullableDecimal/" + hasValue; + var requestUri = "api/SuperDemo/NullableDecimal/"+hasValue; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -4990,7 +5065,7 @@ public System.Nullable GetNullableDecimal(bool hasValue, Action /// GET api/SuperDemo/NullObject /// @@ -5014,7 +5089,7 @@ public System.Nullable GetNullableDecimal(bool hasValue, Action /// GET api/SuperDemo/NullObject /// @@ -5038,7 +5113,7 @@ public DemoWebApi.DemoData.Client.Person GetNullPerson(Action /// GET api/SuperDemo/NullString /// @@ -5054,14 +5129,14 @@ public async Task GetNullStringAsync(Action /// GET api/SuperDemo/NullString /// @@ -5077,20 +5152,20 @@ public string GetNullString(Action h if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/DoubleNullable?location={location}&dd={dd}&de={de} /// public async Task, System.Nullable>> GetPrimitiveNullableAsync(string location, System.Nullable dd, System.Nullable de, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/DoubleNullable?location=" + (location == null ? "" : Uri.EscapeDataString(location)) + (dd.HasValue ? "&dd=" + dd.Value.ToString() : String.Empty) + (de.HasValue ? "&de=" + de.Value.ToString() : String.Empty); + var requestUri = "api/SuperDemo/DoubleNullable?location="+(location == null ? "" : Uri.EscapeDataString(location))+(dd.HasValue?"&dd="+dd.Value.ToString():String.Empty)+(de.HasValue?"&de="+de.Value.ToString():String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5108,13 +5183,13 @@ public string GetNullString(Action h responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/DoubleNullable?location={location}&dd={dd}&de={de} /// public System.Tuple, System.Nullable> GetPrimitiveNullable(string location, System.Nullable dd, System.Nullable de, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/DoubleNullable?location=" + (location == null ? "" : Uri.EscapeDataString(location)) + (dd.HasValue ? "&dd=" + dd.Value.ToString() : String.Empty) + (de.HasValue ? "&de=" + de.Value.ToString() : String.Empty); + var requestUri = "api/SuperDemo/DoubleNullable?location="+(location == null ? "" : Uri.EscapeDataString(location))+(dd.HasValue?"&dd="+dd.Value.ToString():String.Empty)+(de.HasValue?"&de="+de.Value.ToString():String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -5132,13 +5207,13 @@ public string GetNullString(Action h responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/DoubleNullable2?dd={dd}&de={de} /// public async Task, System.Nullable>> GetPrimitiveNullable2Async(System.Nullable dd, System.Nullable de, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/DoubleNullable2?" + (dd.HasValue ? "dd=" + dd.Value.ToString() : String.Empty) + (de.HasValue ? "&de=" + de.Value.ToString() : String.Empty); + var requestUri = "api/SuperDemo/DoubleNullable2?"+(dd.HasValue?"dd="+dd.Value.ToString():String.Empty)+(de.HasValue?"&de="+de.Value.ToString():String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5156,13 +5231,13 @@ public string GetNullString(Action h responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/DoubleNullable2?dd={dd}&de={de} /// public System.Tuple, System.Nullable> GetPrimitiveNullable2(System.Nullable dd, System.Nullable de, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/DoubleNullable2?" + (dd.HasValue ? "dd=" + dd.Value.ToString() : String.Empty) + (de.HasValue ? "&de=" + de.Value.ToString() : String.Empty); + var requestUri = "api/SuperDemo/DoubleNullable2?"+(dd.HasValue?"dd="+dd.Value.ToString():String.Empty)+(de.HasValue?"&de="+de.Value.ToString():String.Empty); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -5180,7 +5255,7 @@ public string GetNullString(Action h responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/sbyte /// @@ -5202,7 +5277,7 @@ public async Task GetsbyteAsync(Action /// GET api/SuperDemo/sbyte /// @@ -5224,7 +5299,7 @@ public sbyte Getsbyte(Action handleH responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/short /// @@ -5246,7 +5321,7 @@ public async Task GetShortAsync(Action /// GET api/SuperDemo/short /// @@ -5268,13 +5343,13 @@ public short GetShort(Action handleH responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/stringArrayQ?a={a} /// public async Task GetStringArrayQAsync(string[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/stringArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/stringArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5292,13 +5367,13 @@ public async Task GetStringArrayQAsync(string[] a, Action /// GET api/SuperDemo/stringArrayQ?a={a} /// public string[] GetStringArrayQ(string[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/stringArrayQ?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/stringArrayQ?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -5316,13 +5391,13 @@ public string[] GetStringArrayQ(string[] a, Action /// GET api/SuperDemo/stringArrayQ2?a={a} /// public async Task GetStringArrayQ2Async(string[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/stringArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/stringArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5340,13 +5415,13 @@ public async Task GetStringArrayQ2Async(string[] a, Action /// GET api/SuperDemo/stringArrayQ2?a={a} /// public string[] GetStringArrayQ2(string[] a, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/stringArrayQ2?" + String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); + var requestUri = "api/SuperDemo/stringArrayQ2?"+String.Join("&", a.Select(k => $"a={Uri.EscapeDataString(k.ToString())}")); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -5364,7 +5439,7 @@ public string[] GetStringArrayQ2(string[] a, Action /// GET api/SuperDemo/TextStream /// @@ -5377,7 +5452,7 @@ public string[] GetStringArrayQ2(string[] a, Action /// GET api/SuperDemo/TextStream /// @@ -5390,7 +5465,7 @@ public System.Net.Http.HttpResponseMessage GetTextStream(Action /// GET api/SuperDemo/uint /// @@ -5412,7 +5487,7 @@ public async Task GetUintAsync(Action /// GET api/SuperDemo/uint /// @@ -5434,7 +5509,7 @@ public uint GetUint(Action handleHea responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ulong /// @@ -5456,7 +5531,7 @@ public async Task GetulongAsync(Action /// GET api/SuperDemo/ulong /// @@ -5478,7 +5553,7 @@ public ulong Getulong(Action handleH responseMessage.Dispose(); } } - + /// /// GET api/SuperDemo/ushort /// @@ -5500,7 +5575,7 @@ public async Task GetUShortAsync(Action /// GET api/SuperDemo/ushort /// @@ -5522,7 +5597,7 @@ public ushort GetUShort(Action handl responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/ActionResult /// @@ -5534,7 +5609,7 @@ public ushort GetUShort(Action handl responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/SuperDemo/ActionResult /// @@ -5546,7 +5621,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult(Action /// POST api/SuperDemo/PostActionResult2 /// @@ -5564,7 +5639,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult(Action /// POST api/SuperDemo/PostActionResult2 /// @@ -5582,7 +5657,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult2(string s, Action /// POST api/SuperDemo/PostActionResult3 /// @@ -5600,7 +5675,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult2(string s, Action /// POST api/SuperDemo/PostActionResult3 /// @@ -5618,7 +5693,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult3(DemoWebApi.DemoData responseMessage.EnsureSuccessStatusCodeEx(); return responseMessage; } - + /// /// POST api/SuperDemo/Collection /// @@ -5645,7 +5720,7 @@ public async Task PostCollectionAsync(DemoWebApi.DemoData.Client.Person[] l responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/Collection /// @@ -5672,13 +5747,13 @@ public int PostCollection(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/enumPost?d={d} /// public async Task PostDayAsync(DemoWebApi.DemoData.Client.Days d, DemoWebApi.DemoData.Client.Days d2, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumPost?d=" + d; + var requestUri = "api/SuperDemo/enumPost?d="+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -5701,13 +5776,13 @@ public int PostCollection(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/enumPost?d={d} /// public DemoWebApi.DemoData.Client.Days[] PostDay(DemoWebApi.DemoData.Client.Days d, DemoWebApi.DemoData.Client.Days d2, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/enumPost?d=" + d; + var requestUri = "api/SuperDemo/enumPost?d="+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -5730,7 +5805,7 @@ public DemoWebApi.DemoData.Client.Days[] PostDay(DemoWebApi.DemoData.Client.Days responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/StringPersonDic /// @@ -5757,7 +5832,7 @@ public async Task PostDictionaryAsync(System.Collections.Generic.IDictionar responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/StringPersonDic /// @@ -5784,7 +5859,7 @@ public int PostDictionary(System.Collections.Generic.IDictionary /// POST api/SuperDemo/Guids /// @@ -5813,7 +5888,7 @@ public int PostDictionary(System.Collections.Generic.IDictionary /// POST api/SuperDemo/Guids /// @@ -5842,7 +5917,7 @@ public System.Guid[] PostGuids(System.Guid[] guids, Action /// POST api/SuperDemo/ICollection /// @@ -5869,7 +5944,7 @@ public async Task PostICollectionAsync(DemoWebApi.DemoData.Client.Person[] responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/ICollection /// @@ -5896,7 +5971,7 @@ public int PostICollection(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/IList /// @@ -5923,7 +5998,7 @@ public async Task PostIListAsync(DemoWebApi.DemoData.Client.Person[] list, responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/IList /// @@ -5950,7 +6025,7 @@ public int PostIList(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/int2d /// @@ -5977,7 +6052,7 @@ public async Task PostInt2DAsync(int[,] a, Action /// POST api/SuperDemo/int2d /// @@ -6004,7 +6079,7 @@ public bool PostInt2D(int[,] a, Action /// POST api/SuperDemo/int2djagged /// @@ -6031,7 +6106,7 @@ public async Task PostInt2DJaggedAsync(int[][] a, Action /// POST api/SuperDemo/int2djagged /// @@ -6058,7 +6133,7 @@ public bool PostInt2DJagged(int[][] a, Action /// POST api/SuperDemo/intArray /// @@ -6085,7 +6160,7 @@ public async Task PostIntArrayAsync(int[] a, Action /// POST api/SuperDemo/intArray /// @@ -6112,7 +6187,7 @@ public bool PostIntArray(int[] a, Action /// POST api/SuperDemo/IReadOnlyCollection /// @@ -6139,7 +6214,7 @@ public async Task PostIReadOnlyCollectionAsync(DemoWebApi.DemoData.Client.P responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/IReadOnlyCollection /// @@ -6166,7 +6241,7 @@ public int PostIReadOnlyCollection(DemoWebApi.DemoData.Client.Person[] list, Act responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/IReadOnlyList /// @@ -6193,7 +6268,7 @@ public async Task PostIReadOnlyListAsync(DemoWebApi.DemoData.Client.Person[ responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/IReadOnlyList /// @@ -6220,7 +6295,7 @@ public int PostIReadOnlyList(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/List /// @@ -6247,7 +6322,7 @@ public async Task PostListAsync(DemoWebApi.DemoData.Client.Person[] list, A responseMessage.Dispose(); } } - + /// /// POST api/SuperDemo/List /// @@ -6274,13 +6349,13 @@ public int PostList(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/PostEmpty/{i} /// public async Task> PostWithQueryButEmptyBodyAsync(string s, int i, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/PostEmpty/" + i; + var requestUri = "api/SuperDemo/PostEmpty/"+i; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -6303,13 +6378,13 @@ public int PostList(DemoWebApi.DemoData.Client.Person[] list, Action /// POST api/SuperDemo/PostEmpty/{i} /// public System.Tuple PostWithQueryButEmptyBody(string s, int i, Action handleHeaders = null) { - var requestUri = "api/SuperDemo/PostEmpty/" + i; + var requestUri = "api/SuperDemo/PostEmpty/"+i; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -6333,19 +6408,19 @@ public System.Tuple PostWithQueryButEmptyBody(string s, int i, Acti } } } - + /// /// https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.3.3 /// Authorize: Bearer /// public partial class Tuple { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -6356,7 +6431,7 @@ public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSeria this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// POST api/Tuple/ChangeName /// @@ -6385,7 +6460,7 @@ public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSeria responseMessage.Dispose(); } } - + /// /// POST api/Tuple/ChangeName /// @@ -6414,7 +6489,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/PeopleCompany4 /// @@ -6438,7 +6513,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/PeopleCompany4 /// @@ -6462,7 +6537,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/PeopleCompany5 /// @@ -6486,7 +6561,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/PeopleCompany5 /// @@ -6510,7 +6585,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/Tuple1 /// @@ -6534,7 +6609,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple /// GET api/Tuple/Tuple1 /// @@ -6558,7 +6633,7 @@ public System.Tuple GetTuple1(Action /// GET api/Tuple/Tuple2 /// @@ -6582,7 +6657,7 @@ public System.Tuple GetTuple1(Action /// GET api/Tuple/Tuple2 /// @@ -6606,7 +6681,7 @@ public System.Tuple GetTuple2(Action /// GET api/Tuple/Tuple3 /// @@ -6630,7 +6705,7 @@ public System.Tuple GetTuple2(Action /// GET api/Tuple/Tuple3 /// @@ -6654,7 +6729,7 @@ public System.Tuple GetTuple3(Action /// GET api/Tuple/Tuple4 /// @@ -6678,7 +6753,7 @@ public System.Tuple GetTuple3(Action /// GET api/Tuple/Tuple4 /// @@ -6702,7 +6777,7 @@ public System.Tuple GetTuple4(Action /// GET api/Tuple/Tuple5 /// @@ -6726,7 +6801,7 @@ public System.Tuple GetTuple4(Action /// GET api/Tuple/Tuple5 /// @@ -6750,7 +6825,7 @@ public System.Tuple GetTuple5(Action /// GET api/Tuple/Tuple6 /// @@ -6774,7 +6849,7 @@ public System.Tuple GetTuple5(Action /// GET api/Tuple/Tuple6 /// @@ -6798,7 +6873,7 @@ public System.Tuple GetTuple6(Actio responseMessage.Dispose(); } } - + /// /// GET api/Tuple/Tuple7 /// @@ -6822,7 +6897,7 @@ public System.Tuple GetTuple6(Actio responseMessage.Dispose(); } } - + /// /// GET api/Tuple/Tuple7 /// @@ -6846,7 +6921,7 @@ public System.Tuple GetTuple7 responseMessage.Dispose(); } } - + /// /// GET api/Tuple/Tuple8 /// @@ -6870,7 +6945,7 @@ public System.Tuple GetTuple7 responseMessage.Dispose(); } } - + /// /// GET api/Tuple/Tuple8 /// @@ -6894,7 +6969,7 @@ public System.Tuple GetTuple7 responseMessage.Dispose(); } } - + /// /// POST api/Tuple/PeopleCompany2 /// @@ -6923,7 +6998,7 @@ public System.Tuple GetTuple7 responseMessage.Dispose(); } } - + /// /// POST api/Tuple/PeopleCompany2 /// @@ -6952,7 +7027,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany2(System.Tuple /// POST api/Tuple/PeopleCompany3 /// @@ -6981,7 +7056,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany2(System.Tuple /// POST api/Tuple/PeopleCompany3 /// @@ -7010,7 +7085,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany3(System.Tuple /// POST api/Tuple/PeopleCompany4 /// @@ -7039,7 +7114,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany3(System.Tuple /// POST api/Tuple/PeopleCompany4 /// @@ -7068,7 +7143,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany4(System.Tuple /// POST api/Tuple/PeopleCompany5 /// @@ -7097,7 +7172,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany4(System.Tuple /// POST api/Tuple/PeopleCompany5 /// @@ -7126,7 +7201,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany5(System.Tuple /// POST api/Tuple/PeopleCompany6 /// @@ -7155,7 +7230,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany5(System.Tuple /// POST api/Tuple/PeopleCompany6 /// @@ -7184,7 +7259,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany6(System.Tuple /// POST api/Tuple/PeopleCompany7 /// @@ -7213,7 +7288,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany6(System.Tuple /// POST api/Tuple/PeopleCompany7 /// @@ -7242,7 +7317,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany7(System.Tuple /// POST api/Tuple/PeopleCompany8 /// @@ -7271,7 +7346,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany7(System.Tuple /// POST api/Tuple/PeopleCompany8 /// @@ -7300,7 +7375,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany8(System.Tuple /// POST api/Tuple/PersonCompany1 /// @@ -7329,7 +7404,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany8(System.Tuple /// POST api/Tuple/PersonCompany1 /// @@ -7358,7 +7433,7 @@ public DemoWebApi.DemoData.Client.Person LinkPersonCompany1(System.Tuple /// POST api/Tuple/Tuple1 /// @@ -7385,7 +7460,7 @@ public async Task PostTuple1Async(System.Tuple tuple, Action /// POST api/Tuple/Tuple1 /// @@ -7412,7 +7487,7 @@ public int PostTuple1(System.Tuple tuple, Action /// POST api/Tuple/Tuple2 /// @@ -7433,14 +7508,14 @@ public async Task PostTuple2Async(System.Tuple tuple, Actio if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// POST api/Tuple/Tuple2 /// @@ -7461,14 +7536,14 @@ public string PostTuple2(System.Tuple tuple, Action /// POST api/Tuple/Tuple3 /// @@ -7489,14 +7564,14 @@ public async Task PostTuple3Async(System.Tuple tupl if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// POST api/Tuple/Tuple3 /// @@ -7517,14 +7592,14 @@ public string PostTuple3(System.Tuple tuple, Action /// POST api/Tuple/Tuple4 /// @@ -7545,14 +7620,14 @@ public async Task PostTuple4Async(System.Tuple /// POST api/Tuple/Tuple4 /// @@ -7573,14 +7648,14 @@ public string PostTuple4(System.Tuple tuple, Action if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// POST api/Tuple/Tuple5 /// @@ -7601,14 +7676,14 @@ public async Task PostTuple5Async(System.Tuple /// POST api/Tuple/Tuple5 /// @@ -7629,14 +7704,14 @@ public string PostTuple5(System.Tuple tuple if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// POST api/Tuple/Tuple6 /// @@ -7657,14 +7732,14 @@ public async Task PostTuple6Async(System.Tuple /// POST api/Tuple/Tuple6 /// @@ -7685,14 +7760,14 @@ public string PostTuple6(System.Tuple /// POST api/Tuple/Tuple7 /// @@ -7713,14 +7788,14 @@ public async Task PostTuple7Async(System.Tuple /// POST api/Tuple/Tuple7 /// @@ -7741,14 +7816,14 @@ public string PostTuple7(System.Tuple /// POST api/Tuple/Tuple8 /// @@ -7769,14 +7844,14 @@ public async Task PostTuple8Async(System.Tuple /// POST api/Tuple/Tuple8 /// @@ -7797,7 +7872,7 @@ public string PostTuple8(System.Tuple /// DELETE api/Values/{id} /// public async Task DeleteAsync(int id, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -7843,13 +7918,13 @@ public async Task DeleteAsync(int id, Action /// DELETE api/Values/{id} /// public void Delete(int id, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -7862,7 +7937,7 @@ public void Delete(int id, Action ha responseMessage.Dispose(); } } - + /// /// Get a list of value /// GET api/Values @@ -7886,7 +7961,7 @@ public async Task GetAsync(Action /// Get a list of value /// GET api/Values @@ -7910,14 +7985,14 @@ public string[] Get(Action handleHea responseMessage.Dispose(); } } - + /// /// Get by both Id and name /// GET api/Values/{id}?name={name} /// public async Task GetAsync(int id, string name, Action handleHeaders = null) { - var requestUri = "api/Values/" + id + "?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Values/"+id+"?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -7927,21 +8002,21 @@ public async Task GetAsync(int id, string name, Action /// Get by both Id and name /// GET api/Values/{id}?name={name} /// public string Get(int id, string name, Action handleHeaders = null) { - var requestUri = "api/Values/" + id + "?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Values/"+id+"?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -7951,20 +8026,20 @@ public string Get(int id, string name, Action /// GET api/Values?name={name} /// public async Task GetAsync(string name, Action handleHeaders = null) { - var requestUri = "api/Values?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Values?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -7974,20 +8049,20 @@ public async Task GetAsync(string name, Action /// GET api/Values?name={name} /// public string Get(string name, Action handleHeaders = null) { - var requestUri = "api/Values?name=" + (name == null ? "" : Uri.EscapeDataString(name)); + var requestUri = "api/Values?name="+(name == null ? "" : Uri.EscapeDataString(name)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -7997,20 +8072,20 @@ public string Get(string name, Action /// GET api/Values/{id} /// public async Task GetAsync(int id, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -8020,20 +8095,20 @@ public async Task GetAsync(int id, Action /// GET api/Values/{id} /// public string Get(int id, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -8043,14 +8118,14 @@ public string Get(int id, Action han if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); using System.IO.StreamReader streamReader = new System.IO.StreamReader(stream); - return streamReader.ReadToEnd(); ; + return streamReader.ReadToEnd();; } finally { responseMessage.Dispose(); } } - + /// /// GET api/Values/Get2 /// @@ -8073,7 +8148,7 @@ public async Task Get2Async(Action /// GET api/Values/Get2 /// @@ -8096,7 +8171,7 @@ public string[] Get2(Action handleHe responseMessage.Dispose(); } } - + /// /// POST api/Values /// @@ -8117,14 +8192,14 @@ public async Task PostAsync(string value, Action /// POST api/Values /// @@ -8145,21 +8220,21 @@ public string Post(string value, Action /// Update with valjue /// PUT api/Values/{id} /// public async Task PutAsync(int id, string value, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -8177,14 +8252,14 @@ public async Task PutAsync(int id, string value, Action /// Update with valjue /// PUT api/Values/{id} /// public void Put(int id, string value, Action handleHeaders = null) { - var requestUri = "api/Values/" + id; + var requestUri = "api/Values/"+id; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); using var requestWriter = new System.IO.StringWriter(); var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); @@ -8206,602 +8281,210 @@ public void Put(int id, string value, Action - /// 2D position - /// with X and Y - /// for Demo - /// + + public struct MyPoint { - - /// - /// X - /// + public double X; - - /// - /// Y - /// + public double Y; } } namespace DemoWebApi.DemoData.Client { - - + + + public class Entity : object + { + + public DemoWebApi.DemoData.Client.Address[] Addresses { get; set; } + + public System.Nullable Id { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + public string Name { get; set; } + + public DemoWebApi.DemoData.Client.PhoneNumber[] PhoneNumbers { get; set; } + + public System.Uri Web { get; set; } + } + public class Address : object { - + public string City { get; set; } - + [System.ComponentModel.DefaultValueAttribute("Australia")] public string Country { get; set; } = "Australia"; - + + public DemoWebApi.DemoData.Client.Entity Entity { get; set; } + + public System.Guid EntityId { get; set; } + public System.Guid Id { get; set; } - + public string PostalCode { get; set; } - + public string State { get; set; } - + public string Street1 { get; set; } - + public string Street2 { get; set; } - + [System.ComponentModel.DefaultValueAttribute(AddressType.Residential)] public DemoWebApi.DemoData.Client.AddressType Type { get; set; } = AddressType.Residential; - - /// - /// It is a field - /// + public DemoWebApi.DemoData.Another.Client.MyPoint Location { get; set; } } - + public enum AddressType { - + Postal, - + Residential, } - + + public class PhoneNumber : object + { + + public System.Guid EntityId { get; set; } + + public string FullNumber { get; set; } + + public System.Guid Id { get; set; } + + public DemoWebApi.DemoData.Client.PhoneType PhoneType { get; set; } + } + + public enum PhoneType + { + + Tel, + + Mobile, + + Skype, + + Fax, + } + + public class Person : DemoWebApi.DemoData.Client.Entity + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] + public System.Nullable Baptised { get; set; } + + public System.Nullable DOB { get; set; } + + public string GivenName { get; set; } + + public string Surname { get; set; } + } + public class Company : DemoWebApi.DemoData.Client.Entity { - - /// - /// BusinessNumber to be serialized as BusinessNum - /// + public string BusinessNumber { get; set; } - + public string BusinessNumberType { get; set; } - - /// - /// Data type: Date - /// + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] public System.DateTimeOffset FoundDate { get; set; } - + public System.DateOnly RegisterDate { get; set; } - + public string[][] TextMatrix { get; set; } - + public int[,] Int2D { get; set; } - + public int[][] Int2DJagged { get; set; } - + public string[] Lines { get; set; } } - + public enum Days { - + Sat = 1, - + Sun = 2, - + Mon = 3, - + Tue = 4, - + Wed = 5, - - /// - /// Thursday - /// + Thu = 6, - + Fri = 7, } - - /// - /// Base class of company and person - /// - public class Entity : object + + public class MimsResult : object { - - /// - /// Multiple addresses - /// - public DemoWebApi.DemoData.Client.Address[] Addresses { get; set; } - - public System.Nullable Id { get; set; } - - /// - /// Name of the entity. - /// Required - /// - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string Name { get; set; } - - public DemoWebApi.DemoData.Client.PhoneNumber[] PhoneNumbers { get; set; } - - public System.Uri Web { get; set; } + + public System.DateTime GeneratedAt { get; set; } + + public string Message { get; set; } + + public T Result { get; set; } + + public bool Success { get; set; } } - - /// - /// To test different serializations against Guid - /// + + public class MyGeneric : object + { + + public K MyK { get; set; } + + public T MyT { get; set; } + + public U MyU { get; set; } + + public string Status { get; set; } + } + public class IdMap : object { - + public System.Guid Id { get; set; } - + public System.Guid IdNotEmitDefaultValue { get; set; } - + public System.Nullable NullableId { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] + public string RequiredName { get; set; } - + public string Text { get; set; } } - - [Newtonsoft.Json.JsonConverterAttribute(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] - public enum MedicalContraindiationResponseTypeReason - { - - M, - - S, - - P, - - I, - - A, - } - - [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] - public enum MedicalContraindiationResponseTypeTypeCode - { - - P, - - T, - } - + public class MimsPackage : object { - - /// - /// Range: inclusive between 10 and 100 - /// + [System.ComponentModel.DefaultValueAttribute(20)] - [System.ComponentModel.DataAnnotations.Range(typeof(System.Int32), "10", "100", ErrorMessage = "KK has to be between 10 and 100.")] + [System.ComponentModel.DataAnnotations.Range(typeof(System.Int32), "10", "100", ErrorMessage="KK has to be between 10 and 100.")] public int KK { get; set; } = 20; - - /// - /// Having an initialized value in the property is not like defining a DefaultValueAttribute. Such intialization happens at run time, - /// and there's no reliable way for a codegen to know if the value is declared by the programmer, or is actually the natural default value like 0. - /// + public int KK2 { get; set; } - + public System.Nullable OptionalEnum { get; set; } - + public System.Nullable OptionalInt { get; set; } - + public DemoWebApi.DemoData.Client.MimsResult Result { get; set; } - + public string Tag { get; set; } } - - public class MimsResult : object - { - - public System.DateTime GeneratedAt { get; set; } - - public string Message { get; set; } - - public T Result { get; set; } - - public bool Success { get; set; } - } - + public enum MyEnumType { - + First = 1, - + Two = 2, } - - public class MyGeneric : object - { - - public K MyK { get; set; } - - public T MyT { get; set; } - - public U MyU { get; set; } - - public string Status { get; set; } - } - - public class MyPeopleDic : object - { - - public System.Collections.Generic.IDictionary AnotherDic { get; set; } - - public System.Collections.Generic.IDictionary Dic { get; set; } - - public System.Collections.Generic.IDictionary IntDic { get; set; } - } - - public class Person : DemoWebApi.DemoData.Client.Entity - { - - /// - /// Data type: Date - /// - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] - public System.Nullable Baptised { get; set; } - - /// - /// Date of Birth. - /// This is optional. - /// - public System.Nullable DOB { get; set; } - - public string GivenName { get; set; } - - public string Surname { get; set; } - } - - public class PhoneNumber : object - { - - public string FullNumber { get; set; } - - public DemoWebApi.DemoData.Client.PhoneType PhoneType { get; set; } - } - - /// - /// Phone type - /// Tel, Mobile, Skyp and Fax - /// - /// - public enum PhoneType - { - - /// - /// Land line - /// - Tel, - - /// - /// Mobile phone - /// - Mobile, - - Skype, - - Fax, - } -} -namespace DemoWebApi.Models.Client -{ - - - public class AddExternalLoginBindingModel : object - { - - /// - /// Required - /// - [System.ComponentModel.DataAnnotations.Required()] - public string ExternalAccessToken { get; set; } - } - - public class ChangePasswordBindingModel : object - { - - /// - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - /// - /// Required - /// String length: inclusive between 6 and 100 - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - - /// - /// Required - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string OldPassword { get; set; } - } - - public class RegisterBindingModel : object - { - - /// - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - /// - /// Required - /// - [System.ComponentModel.DataAnnotations.Required()] - public string Email { get; set; } - - /// - /// Required - /// String length: inclusive between 6 and 100 - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string Password { get; set; } - } - - public class RegisterExternalBindingModel : object - { - - /// - /// Required - /// - [System.ComponentModel.DataAnnotations.Required()] - public string Email { get; set; } - } - - public class RemoveLoginBindingModel : object - { - - /// - /// Required - /// - [System.ComponentModel.DataAnnotations.Required()] - public string LoginProvider { get; set; } - - /// - /// Required - /// - [System.ComponentModel.DataAnnotations.Required()] - public string ProviderKey { get; set; } - } - - public class SetPasswordBindingModel : object - { - - /// - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - /// - /// Required - /// String length: inclusive between 6 and 100 - /// Data type: Password - /// - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - } -} -namespace Fonlow.WebApp.Accounts.Client -{ - - - public class AddExternalLoginBindingModel : object - { - - [System.ComponentModel.DataAnnotations.Required()] - public string ExternalAccessToken { get; set; } - } - - public class ApiKey : object - { - - public System.DateTimeOffset ExpiryTime { get; set; } - - public string Key { get; set; } - } - - public class ChangePasswordBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string OldPassword { get; set; } - } - - public class CustomToken : object - { - - public System.Guid ConnectionId { get; set; } - - public System.DateTimeOffset Stamp { get; set; } - - public string TokenValue { get; set; } - } - - public class ExternalLoginViewModel : object - { - - public string Name { get; set; } - - public string State { get; set; } - - public string Url { get; set; } - } - - public class ManageInfoViewModel : object - { - - public string Email { get; set; } - - public Fonlow.WebApp.Accounts.Client.ExternalLoginViewModel[] ExternalLoginProviders { get; set; } - - public string LocalLoginProvider { get; set; } - - public Fonlow.WebApp.Accounts.Client.UserLoginInfoViewModel[] Logins { get; set; } - } - - public class RegisterBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - public string Email { get; set; } - - public string FullName { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string Password { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - public string UserName { get; set; } - } - - public class RegisterExternalBindingModel : object - { - - [System.ComponentModel.DataAnnotations.Required()] - public string Email { get; set; } - } - - public class RemoveLoginBindingModel : object - { - - [System.ComponentModel.DataAnnotations.Required()] - public string LoginProvider { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - public string ProviderKey { get; set; } - } - - public class ResetPasswordViewModel : object - { - - public string Code { get; set; } - - public string ConfirmPassword { get; set; } - - public string Email { get; set; } - - public string Password { get; set; } - } - - public class SetPasswordBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength = 6, ErrorMessage = "The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - } - - public class SetUserPasswordBindingModel : Fonlow.WebApp.Accounts.Client.SetPasswordBindingModel - { - - public string UserId { get; set; } - } - - public class TokenResponseModel : object - { - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string AccessToken { get; set; } - - public System.Guid ConnectionId { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string Expires { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public int ExpiresIn { get; set; } - - public string RefreshToken { get; set; } - - public string Scope { get; set; } - - public string State { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string TokenType { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string Username { get; set; } - } - - public class UserInfoViewModel : object - { - - public System.DateTime CreatedUtc { get; set; } - - public string Email { get; set; } - - public string FullName { get; set; } - - public bool HasRegistered { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public System.Guid Id { get; set; } - - public string LoginProvider { get; set; } - - public string[] Roles { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string UserName { get; set; } - } - - public class UserLoginInfoViewModel : object - { - - public string LoginProvider { get; set; } - - public string ProviderKey { get; set; } - } } namespace Core3WebApi.Controllers.Client { @@ -8812,16 +8495,16 @@ namespace Core3WebApi.Controllers.Client using System.Net.Http; using Newtonsoft.Json; using Fonlow.Net.Http; - - + + public partial class Statistics { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -8832,7 +8515,7 @@ public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings json this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// GET api/Statistics/distribution /// @@ -8856,7 +8539,7 @@ public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings json responseMessage.Dispose(); } } - + /// /// GET api/Statistics/distribution /// @@ -8891,19 +8574,19 @@ namespace DemoCoreWeb.Controllers.Client using System.Net.Http; using Newtonsoft.Json; using Fonlow.Net.Http; - - + + /// /// Authorize: Bearer /// public partial class SpecialTypes { - + private System.Net.Http.HttpClient client; - + private JsonSerializerSettings jsonSerializerSettings; - - public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings = null) + + public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -8914,7 +8597,7 @@ public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings js this.client = client; this.jsonSerializerSettings = jsonSerializerSettings; } - + /// /// Anonymous Dynamic of C# /// GET api/SpecialTypes/AnonymousDynamic @@ -8940,7 +8623,7 @@ public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings js responseMessage.Dispose(); } } - + /// /// Anonymous Dynamic of C# /// GET api/SpecialTypes/AnonymousDynamic @@ -8966,7 +8649,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action /// GET api/SpecialTypes/AnonymousDynamic2 /// @@ -8990,7 +8673,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action /// GET api/SpecialTypes/AnonymousDynamic2 /// @@ -9014,7 +8697,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action /// GET api/SpecialTypes/AnonymousObject /// @@ -9038,7 +8721,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action /// GET api/SpecialTypes/AnonymousObject /// @@ -9062,7 +8745,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action /// GET api/SpecialTypes/AnonymousObject2 /// @@ -9086,7 +8769,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action /// GET api/SpecialTypes/AnonymousObject2 /// @@ -9110,7 +8793,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action /// POST api/SpecialTypes/AnonymousObject /// @@ -9139,7 +8822,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action /// POST api/SpecialTypes/AnonymousObject /// @@ -9168,7 +8851,7 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb responseMessage.Dispose(); } } - + /// /// POST api/SpecialTypes/AnonymousObject2 /// @@ -9197,7 +8880,7 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb responseMessage.Dispose(); } } - + /// /// POST api/SpecialTypes/AnonymousObject2 /// @@ -9228,6 +8911,106 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject2(Newtonsoft.Json.Linq.JO } } } +namespace Fonlow.AspNetCore.OAuth2.Client +{ + + + public class RequestBase : object + { + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + public string GrantType { get; set; } + } +} +namespace Fonlow.WebApp.Accounts.Client +{ + + + public class UserInfoViewModel : object + { + + public System.DateTime CreatedUtc { get; set; } + + public string Email { get; set; } + + public string FullName { get; set; } + + public bool HasRegistered { get; set; } + + public System.Guid Id { get; set; } + + public string LoginProvider { get; set; } + + public string[] Roles { get; set; } + + public string UserName { get; set; } + } + + public class ChangePasswordBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string ConfirmPassword { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string NewPassword { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string OldPassword { get; set; } + } + + public class RegisterBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string ConfirmPassword { get; set; } + + public string Email { get; set; } + + public string FullName { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string Password { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + public string UserName { get; set; } + } + + public class ResetPasswordViewModel : object + { + + public string Code { get; set; } + + public string ConfirmPassword { get; set; } + + public string Email { get; set; } + + public string Password { get; set; } + } + + public class SetPasswordBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string ConfirmPassword { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + public string NewPassword { get; set; } + } + + public class SetUserPasswordBindingModel : Fonlow.WebApp.Accounts.Client.SetPasswordBindingModel + { + + public string UserId { get; set; } + } +} namespace Fonlow.Net.Http { diff --git a/DemoWebApi.DemoDataCore/AccountBindingModels.cs b/DemoWebApi.DemoDataCore/AccountBindingModels.cs index 8ca8184..160ce13 100644 --- a/DemoWebApi.DemoDataCore/AccountBindingModels.cs +++ b/DemoWebApi.DemoDataCore/AccountBindingModels.cs @@ -1,12 +1,11 @@ using System; using System.ComponentModel.DataAnnotations; -using Newtonsoft.Json; namespace DemoWebApi.Models { // Models used as parameters to AccountController actions. - [JsonObject] + public class AddExternalLoginBindingModel { [Required] @@ -14,16 +13,14 @@ public class AddExternalLoginBindingModel public string ExternalAccessToken { get; set; } } - [JsonObject] + public class ChangePasswordBindingModel { - [JsonProperty(PropertyName ="OldPwd")] [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } - [JsonProperty(Required = Required.Always)] [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] @@ -36,7 +33,7 @@ public class ChangePasswordBindingModel public string ConfirmPassword { get; set; } } - [JsonObject] + public class RegisterBindingModel { [Required] @@ -55,7 +52,7 @@ public class RegisterBindingModel public string ConfirmPassword { get; set; } } - [JsonObject] + public class RegisterExternalBindingModel { [Required] @@ -63,7 +60,7 @@ public class RegisterExternalBindingModel public string Email { get; set; } } - [JsonObject] + public class RemoveLoginBindingModel { [Required] @@ -75,7 +72,7 @@ public class RemoveLoginBindingModel public string ProviderKey { get; set; } } - [JsonObject] + public class SetPasswordBindingModel { [Required] diff --git a/DemoWebApi.DemoDataCore/DemoWebApi.DemoDataCore.csproj b/DemoWebApi.DemoDataCore/DemoWebApi.DemoDataCore.csproj index b8d6e8e..5c3b0c4 100644 --- a/DemoWebApi.DemoDataCore/DemoWebApi.DemoDataCore.csproj +++ b/DemoWebApi.DemoDataCore/DemoWebApi.DemoDataCore.csproj @@ -9,8 +9,4 @@ 1701;1702;1705;1591 - - - - diff --git a/DemoWebApi.DemoDataCore/Entities.cs b/DemoWebApi.DemoDataCore/Entities.cs index 03686a6..185d406 100644 --- a/DemoWebApi.DemoDataCore/Entities.cs +++ b/DemoWebApi.DemoDataCore/Entities.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Runtime.Serialization; using System.Collections.ObjectModel; -using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace DemoWebApi.DemoData @@ -313,7 +312,6 @@ public class MyGeneric } [DataContract(Namespace = Constants.DataNamespace)] - [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] public enum MedicalContraindiationResponseTypeReason { @@ -376,7 +374,6 @@ namespace DemoWebApi.DemoData.Another /// with X and Y /// for Demo /// - [JsonObject] public struct MyPoint { /// diff --git a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj index 03c0b49..de1a572 100644 --- a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj +++ b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj @@ -24,7 +24,11 @@ - + + + + + diff --git a/Fonlow.WebApp.Accounts/UsernameModel.cs b/Fonlow.WebApp.Accounts/UsernameModel.cs index 0e025a4..0439d62 100644 --- a/Fonlow.WebApp.Accounts/UsernameModel.cs +++ b/Fonlow.WebApp.Accounts/UsernameModel.cs @@ -1,4 +1,6 @@ -using System.Runtime.Serialization; +using Fonlow.AspNetCore.OAuth2; +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; using System.Text.Json.Serialization; namespace Fonlow.WebApp.Accounts @@ -7,24 +9,10 @@ namespace Fonlow.WebApp.Accounts /// https://datatracker.ietf.org/doc/html/rfc7519 JWT /// https://www.ietf.org/rfc/rfc6749.txt, The OAuth 2.0 Authorization Framework /// - /// The controller has better to be using AddNewtonsoftJson to horner DataMemberAttribute. .NET Core apparently like JsonPropertyNameAttribute more. - [DataContract] - public class TokenResponseModel + public class TokenResponseModel : AccessTokenResponse { - [JsonPropertyName("access_token")] - [DataMember(Name = "access_token", IsRequired = true)] - public string AccessToken { get; set; } - - [JsonPropertyName("token_type")] - [DataMember(Name = "token_type", IsRequired = true)] - public string TokenType { get; set; } - - [JsonPropertyName("expires_in")] - [DataMember(Name = "expires_in", IsRequired = true)] - public int ExpiresIn { get; set; } - [JsonPropertyName("username")] - [DataMember(Name = "username", IsRequired = true)] + [Required] public string Username { get; set; } //[DataMember(Name = "issued", IsRequired = true)] @@ -34,21 +22,9 @@ public class TokenResponseModel /// For human readable. The app codes generaly use expires_in /// [JsonPropertyName("expires")] - [DataMember(Name = "expires", IsRequired = true)] + [Required] public string Expires { get; set; } - [JsonPropertyName("refresh_token")] - [DataMember(Name = "refresh_token")] - public string RefreshToken { get; set; } - - [JsonPropertyName("scope")] - [DataMember(Name = "scope")] - public string Scope { get; set; } - - [JsonPropertyName("state")] - [DataMember(Name = "state")] - public string State {get;set;} - /// /// Custom /// diff --git a/PublishMySqlPluginToWebApi.ps1 b/PublishMySqlPluginToWebApi.ps1 index ffd0bc8..42536d2 100644 --- a/PublishMySqlPluginToWebApi.ps1 +++ b/PublishMySqlPluginToWebApi.ps1 @@ -1,4 +1,6 @@ -#Launch WebApi Website and POST a request for generating client APIs +# Because of decoupling from DB engines, the Web API needs the assemblies of a specific DB engine plugin. +# This script is to publish MySql plugin to the Web API release build during development. +# During deployment, system admin may switch to a DB engine with a bare deployment of the Web API, and copy the plugin assmeblies, and then adjust the appsetting.json file. Set-Location $PSScriptRoot $netVersion = "net8.0" $RuntimeId = ([System.Runtime.InteropServices.RuntimeInformation]::RuntimeIdentifier.ToString()) diff --git a/Tests/AuthRemoteTests/AuthRemoteTests.csproj b/Tests/AuthRemoteTests/AuthRemoteTests.csproj index c834de5..1a2555d 100644 --- a/Tests/AuthRemoteTests/AuthRemoteTests.csproj +++ b/Tests/AuthRemoteTests/AuthRemoteTests.csproj @@ -22,7 +22,7 @@ - + all diff --git a/Tests/AuthTests/AuthTests.csproj b/Tests/AuthTests/AuthTests.csproj index 3f22f56..79d14b4 100644 --- a/Tests/AuthTests/AuthTests.csproj +++ b/Tests/AuthTests/AuthTests.csproj @@ -21,7 +21,7 @@ - + all diff --git a/Tests/AuthTests/TokenFacts.cs b/Tests/AuthTests/TokenFacts.cs index 1702834..3165cf2 100644 --- a/Tests/AuthTests/TokenFacts.cs +++ b/Tests/AuthTests/TokenFacts.cs @@ -48,6 +48,16 @@ public TokenFacts(TokenTestsFixture fixture, ITestOutputHelper output) readonly int clockSkewSeconds; + [Fact] + public void TestAccessTokenOnce() + { + var tokenText = GetTokenWithNewClient(baseUri, "admin", "Pppppp*8"); + Assert.NotEmpty(tokenText); + + var toeknModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); + Assert.NotNull(toeknModel.AccessToken); + } + [Fact] public void Test100SiginWithNewHttpClient() { diff --git a/Tests/IntegrationTestsCore/IntegrationTestsCore.csproj b/Tests/IntegrationTestsCore/IntegrationTestsCore.csproj index ec57bde..ca4f89e 100644 --- a/Tests/IntegrationTestsCore/IntegrationTestsCore.csproj +++ b/Tests/IntegrationTestsCore/IntegrationTestsCore.csproj @@ -28,7 +28,7 @@ - + diff --git a/Tests/PetStoreApiTests/PetStoreApiTests.csproj b/Tests/PetStoreApiTests/PetStoreApiTests.csproj index 55e860c..291f868 100644 --- a/Tests/PetStoreApiTests/PetStoreApiTests.csproj +++ b/Tests/PetStoreApiTests/PetStoreApiTests.csproj @@ -21,7 +21,7 @@ - + From d997a2ea6e7c2f13de151a40eed35ac38850e388 Mon Sep 17 00:00:00 2001 From: Zijian Date: Fri, 5 Jul 2024 09:36:33 +1000 Subject: [PATCH 2/5] auth models ok --- .../src/clientapi/WebApiCoreNg2ClientAuto.ts | 533 +++- AuthEF.sln | 9 +- Core3WebApi/CodeGen.json | 8 +- Core3WebApi/Controllers/AuthController.cs | 3 +- .../Controllers/PolymorphismController.cs | 92 + Core3WebApi/Core3WebApi.csproj | 3 +- .../Helpers/OAuth2RequestBinderProvider.cs | 91 + .../CoreWebApi.ClientApi.csproj | 5 +- CoreWebApi.ClientApi/PolymorphismClient.cs | 305 ++ CoreWebApi.ClientApi/WebApiClientAuto.cs | 2533 +++++++---------- DemoWebApi.DemoDataCore/Entities.cs | 3 + Fonlow.AspNetCore.Identity/OAuth2Models.cs | 102 + .../Fonlow.Auth.PayloadConverters.csproj | 8 + Fonlow.Auth.PayloadConverters/Models.cs | 96 + .../TokenRequestConverter.cs | 129 + .../TokenResponseConverter.cs | 109 + .../Fonlow.WebApp.Accounts.csproj | 1 + Fonlow.WebApp.Accounts/UsernameModel.cs | 4 +- PublishMySqlPluginToWebApiDebug.ps1 | 8 + .../DateTypesIntegration.cs | 280 -- .../DotNetCoreSpecial.cs | 57 - .../EntitiesApiIntegration.cs | 14 - .../IntegrationTestShared.projitems | 5 - .../SpecialTypesApiIntegration.cs | 78 - .../SuperDemoIntegration.cs | 556 ---- .../TupleApiIntegration.cs | 201 -- .../IntegrationTestsCore/DateTypesFixture.cs | 24 - Tests/IntegrationTestsCore/EntitiesFixture.cs | 8 +- Tests/IntegrationTestsCore/HeroesFixture.cs | 9 +- .../PolymorphismApiIntegration.cs | 133 + .../PolymorphismFixture.cs | 25 + .../SpecialTypesFixture.cs | 15 - .../IntegrationTestsCore/SuperDemoFixture.cs | 24 - Tests/IntegrationTestsCore/TupleFixture.cs | 23 - .../AuthModelsConvertersTests.cs | 76 + Tests/ModelsUnitTests/ModelsUnitTests.csproj | 32 + 36 files changed, 2663 insertions(+), 2939 deletions(-) create mode 100644 Core3WebApi/Controllers/PolymorphismController.cs create mode 100644 Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs create mode 100644 CoreWebApi.ClientApi/PolymorphismClient.cs create mode 100644 Fonlow.AspNetCore.Identity/OAuth2Models.cs create mode 100644 Fonlow.Auth.PayloadConverters/Fonlow.Auth.PayloadConverters.csproj create mode 100644 Fonlow.Auth.PayloadConverters/Models.cs create mode 100644 Fonlow.Auth.PayloadConverters/TokenRequestConverter.cs create mode 100644 Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs create mode 100644 PublishMySqlPluginToWebApiDebug.ps1 delete mode 100644 Tests/IntegrationTestShared/DateTypesIntegration.cs delete mode 100644 Tests/IntegrationTestShared/DotNetCoreSpecial.cs delete mode 100644 Tests/IntegrationTestShared/SpecialTypesApiIntegration.cs delete mode 100644 Tests/IntegrationTestShared/SuperDemoIntegration.cs delete mode 100644 Tests/IntegrationTestShared/TupleApiIntegration.cs delete mode 100644 Tests/IntegrationTestsCore/DateTypesFixture.cs create mode 100644 Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs create mode 100644 Tests/IntegrationTestsCore/PolymorphismFixture.cs delete mode 100644 Tests/IntegrationTestsCore/SpecialTypesFixture.cs delete mode 100644 Tests/IntegrationTestsCore/SuperDemoFixture.cs delete mode 100644 Tests/IntegrationTestsCore/TupleFixture.cs create mode 100644 Tests/ModelsUnitTests/AuthModelsConvertersTests.cs create mode 100644 Tests/ModelsUnitTests/ModelsUnitTests.csproj diff --git a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts index f485279..602106d 100644 --- a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts +++ b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts @@ -2,149 +2,17 @@ import { Injectable, Inject } from '@angular/core'; import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; export namespace DemoWebApi_Controllers_Client { - export interface Hero { - id?: string | null; - name?: string | null; - } - -} - -export namespace DemoWebApi_DemoData_Client { - export interface Entity { - addresses?: Array; - id?: string | null; - name: string; - phoneNumbers?: Array; - web?: string | null; - } - - export interface Person extends DemoWebApi_DemoData_Client.Entity { - baptised?: Date | null; - dob?: Date | null; - givenName?: string | null; - surname?: string | null; - } - - export interface Company extends DemoWebApi_DemoData_Client.Entity { - businessNumber?: string | null; - businessNumberType?: string | null; - foundDate?: Date | null; - registerDate?: Date | null; - textMatrix?: Array>; - int2D?: number[][]; - int2DJagged?: Array>; - lines?: Array; - } - - export enum Days { Sat = 1, Sun = 2, Mon = 3, Tue = 4, Wed = 5, Thu = 6, Fri = 7 } - - export interface MimsResult { - generatedAt?: Date | null; - message?: string | null; - result?: T; - success?: boolean | null; - } - - export interface MyGeneric { - myK?: K; - myT?: T; - myU?: U; - status?: string | null; - } - - export interface IdMap { - id?: string | null; - idNotEmitDefaultValue?: string | null; - nullableId?: string | null; - requiredName?: string | null; - text?: string | null; - } - - export interface MimsPackage { - kk?: number | null; - kK2?: number | null; - optionalEnum?: number | null; - optionalInt?: number | null; - result?: DemoWebApi_DemoData_Client.MimsResult; - tag?: string | null; - } - -} - -export namespace Core3WebApi_Controllers_Client { - @Injectable() - export class Statistics { - constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { - } - - /** - * GET api/Statistics/distribution - */ - getDistribution(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/Statistics/distribution', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - } - -} - -export namespace DemoCoreWeb_Controllers_Client { /** - * Authorize: Bearer + * Complex hero type */ - @Injectable() - export class SpecialTypes { - constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { - } - - /** - * Anonymous Dynamic of C# - * GET api/SpecialTypes/AnonymousDynamic - * @return {any} dyanmic things - */ - getAnonymousDynamic(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousDynamic2 - */ - getAnonymousDynamic2(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousObject - */ - getAnonymousObject(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * GET api/SpecialTypes/AnonymousObject2 - */ - getAnonymousObject2(headersHandler?: () => HttpHeaders): Observable> { - return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); - } - - /** - * POST api/SpecialTypes/AnonymousObject - */ - postAnonymousObject(obj: any, headersHandler?: () => HttpHeaders): Observable> { - return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); - } + export interface Hero { - /** - * POST api/SpecialTypes/AnonymousObject2 - */ - postAnonymousObject2(obj: any, headersHandler?: () => HttpHeaders): Observable> { - return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject2', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); - } + /** Type: long, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 */ + id?: string | null; + name?: string | null; } -} - -export namespace DemoWebApi_Controllers_Client { /** * Manage user accounts stored in ASP.NET Core Identity database. @@ -1485,37 +1353,309 @@ export namespace DemoWebApi_Controllers_Client { } +export namespace DemoWebApi_DemoData_Another_Client { + + /** + * 2D position + * with X and Y + * for Demo + */ + export interface MyPoint { + + /** + * X + * Type: double + */ + x: number; + + /** + * Y + * Type: double + */ + y: number; + } + +} + +export namespace DemoWebApi_DemoData_Client { + export interface Address { + city?: string | null; + country?: string | null; + + /** Type: GUID */ + id?: string | null; + postalCode?: string | null; + state?: string | null; + street1?: string | null; + street2?: string | null; + type?: DemoWebApi_DemoData_Client.AddressType | null; + + /** + * It is a field + */ + location?: DemoWebApi_DemoData_Another_Client.MyPoint; + } + + export enum AddressType { Postal, Residential } + + export interface Company extends DemoWebApi_DemoData_Client.Entity { + + /** + * BusinessNumber to be serialized as BusinessNum + */ + BusinessNum?: string | null; + businessNumberType?: string | null; + + /** Data type: Date */ + foundDate?: Date | null; + + /** Type: DateOnly */ + registerDate?: Date | null; + textMatrix?: Array>; + int2D?: number[][]; + int2DJagged?: Array>; + lines?: Array; + } + + export enum Days { + Sat = 1, + Sun = 2, + Mon = 3, + Tue = 4, + Wed = 5, + + /** + * Thursday + */ + Thu = 6, + Fri = 7 + } + + + /** + * Base class of company and person + */ + export interface Entity { + + /** + * Multiple addresses + */ + addresses?: Array; + id?: string | null; + + /** + * Name of the entity. + * Required + */ + name: string; + phoneNumbers?: Array; + + /** Type: Uri */ + web?: string | null; + } + + + /** + * To test different serializations against Guid + */ + export interface IdMap { + + /** Type: GUID */ + id?: string | null; + + /** Type: GUID */ + idNotEmitDefaultValue?: string | null; + nullableId?: string | null; + requiredName: string; + text?: string | null; + } + + export enum MedicalContraindiationResponseTypeReason { M = "Mm", S = "Ss", P = "Pp", I = "I", A = "A" } + + export enum MedicalContraindiationResponseTypeTypeCode { P = "P", T = "Tt" } + + export interface MimsPackage { + + /** + * Type: int + * Range: inclusive between 10 and 100 + */ + kk?: number | null; + + /** + * Having an initialized value in the property is not like defining a DefaultValueAttribute. Such intialization happens at run time, + * and there's no reliable way for a codegen to know if the value is declared by the programmer, or is actually the natural default value like 0. + * Type: int, -2,147,483,648 to 2,147,483,647 + */ + kK2?: number | null; + optionalEnum?: DemoWebApi_DemoData_Client.MyEnumType | null; + optionalInt?: number | null; + result?: DemoWebApi_DemoData_Client.MimsResult; + tag?: string | null; + } + + export interface MimsResult { + generatedAt?: Date | null; + message?: string | null; + result?: T; + success?: boolean | null; + } + + export enum MyEnumType { First = 1, Two = 2 } + + export interface MyGeneric { + myK?: K; + myT?: T; + myU?: U; + status?: string | null; + } + + export interface MyPeopleDic { + anotherDic?: {[id: string]: string }; + dic?: {[id: string]: DemoWebApi_DemoData_Client.Person }; + intDic?: {[id: number]: string }; + } + + export interface Person extends DemoWebApi_DemoData_Client.Entity { + + /** Data type: Date */ + baptised?: Date | null; + + /** + * Date of Birth. + * This is optional. + */ + dob?: Date | null; + givenName?: string | null; + surname?: string | null; + } + + export interface PhoneNumber { + fullNumber?: string | null; + phoneType?: DemoWebApi_DemoData_Client.PhoneType | null; + } + + + /** + * Phone type + * Tel, Mobile, Skyp and Fax + */ + export enum PhoneType { + + /** + * Land line + */ + Tel, + + /** + * Mobile phone + */ + Mobile, + Skype, + Fax + } + +} + +export namespace Fonlow_AspNetCore_Identity_Client { + export interface IdentitySeeding { + roles?: Array; + users?: Array; + } + + export interface UserInitModel extends Fonlow_AspNetCore_Identity_Client.UsernameModel { + email?: string | null; + fullName?: string | null; + role?: string | null; + } + + export interface UsernameModel { + password?: string | null; + username?: string | null; + } + +} + export namespace Fonlow_AspNetCore_OAuth2_Client { + export interface AccessTokenResponse { + access_token?: string | null; + expires_in?: number | null; + refresh_token?: string | null; + scope?: string | null; + token_type?: string | null; + } + + export interface RefreshAccessTokenRequest extends Fonlow_AspNetCore_OAuth2_Client.RequestBase { + refresh_token?: string | null; + scope?: string | null; + } + export interface RequestBase { - grantType: string; + grant_type?: string | null; + } + + export interface ROPCRequst extends Fonlow_AspNetCore_OAuth2_Client.RequestBase { + password?: string | null; + scope?: string | null; + username?: string | null; + } + + export interface TokenResponseBase { + token_type?: string | null; } } export namespace Fonlow_WebApp_Accounts_Client { - export interface UserInfoViewModel { - createdUtc?: Date | null; - email?: string | null; - fullName?: string | null; - hasRegistered?: boolean | null; - id?: string | null; - loginProvider?: string | null; - roles?: Array; - userName?: string | null; + export interface AddExternalLoginBindingModel { + externalAccessToken?: string | null; + } + + export interface ApiKey { + expiryTime?: Date | null; + key?: string | null; } export interface ChangePasswordBindingModel { confirmPassword?: string | null; - newPassword: string; - oldPassword: string; + newPassword?: string | null; + oldPassword?: string | null; + } + + export interface CustomToken { + connectionId?: string | null; + stamp?: Date | null; + tokenValue?: string | null; + } + + export interface ExternalLoginViewModel { + name?: string | null; + state?: string | null; + url?: string | null; + } + + export interface ManageInfoViewModel { + email?: string | null; + externalLoginProviders?: Array; + localLoginProvider?: string | null; + logins?: Array; } export interface RegisterBindingModel { confirmPassword?: string | null; email?: string | null; fullName?: string | null; - password: string; - userName: string; + password?: string | null; + userName?: string | null; + } + + export interface RegisterExternalBindingModel { + email?: string | null; + } + + export interface RemoveLoginBindingModel { + loginProvider?: string | null; + providerKey?: string | null; } export interface ResetPasswordViewModel { @@ -1527,12 +1667,101 @@ export namespace Fonlow_WebApp_Accounts_Client { export interface SetPasswordBindingModel { confirmPassword?: string | null; - newPassword: string; + newPassword?: string | null; } export interface SetUserPasswordBindingModel extends Fonlow_WebApp_Accounts_Client.SetPasswordBindingModel { userId?: string | null; } + export interface UserInfoViewModel { + createdUtc?: Date | null; + email?: string | null; + fullName?: string | null; + hasRegistered?: boolean | null; + id: string; + loginProvider?: string | null; + roles?: Array; + userName: string; + } + + export interface UserLoginInfoViewModel { + loginProvider?: string | null; + providerKey?: string | null; + } + +} + +export namespace Core3WebApi_Controllers_Client { + @Injectable() + export class Statistics { + constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { + } + + /** + * GET api/Statistics/distribution + */ + getDistribution(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/Statistics/distribution', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + } + +} + +export namespace DemoCoreWeb_Controllers_Client { + + /** + * Authorize: Bearer + */ + @Injectable() + export class SpecialTypes { + constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { + } + + /** + * Anonymous Dynamic of C# + * GET api/SpecialTypes/AnonymousDynamic + * @return {any} dyanmic things + */ + getAnonymousDynamic(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousDynamic2 + */ + getAnonymousDynamic2(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousDynamic2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousObject + */ + getAnonymousObject(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * GET api/SpecialTypes/AnonymousObject2 + */ + getAnonymousObject2(headersHandler?: () => HttpHeaders): Observable> { + return this.http.get(this.baseUri + 'api/SpecialTypes/AnonymousObject2', { headers: headersHandler ? headersHandler() : undefined, observe: 'response', responseType: 'text' }); + } + + /** + * POST api/SpecialTypes/AnonymousObject + */ + postAnonymousObject(obj: any, headersHandler?: () => HttpHeaders): Observable> { + return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); + } + + /** + * POST api/SpecialTypes/AnonymousObject2 + */ + postAnonymousObject2(obj: any, headersHandler?: () => HttpHeaders): Observable> { + return this.http.post(this.baseUri + 'api/SpecialTypes/AnonymousObject2', JSON.stringify(obj), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }), observe: 'response', responseType: 'text' }); + } + } + } diff --git a/AuthEF.sln b/AuthEF.sln index 539d61f..31dd00a 100644 --- a/AuthEF.sln +++ b/AuthEF.sln @@ -60,7 +60,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PetStoreApiTests", "Tests\P EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fonlow.EntityFrameworkCore.PostgreSQL", "Fonlow.EntityFrameworkCore.PostgreSQL\Fonlow.EntityFrameworkCore.PostgreSQL.csproj", "{CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelsUnitTests", "Tests\ModelsUnitTests\ModelsUnitTests.csproj", "{22AC790B-B412-40BB-880F-468725DA3843}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ModelsUnitTests", "Tests\ModelsUnitTests\ModelsUnitTests.csproj", "{22AC790B-B412-40BB-880F-468725DA3843}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fonlow.Auth.PayloadConverters", "Fonlow.Auth.PayloadConverters\Fonlow.Auth.PayloadConverters.csproj", "{2D30E62C-6D5A-4D77-BF2B-A477B799F338}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -148,6 +150,10 @@ Global {22AC790B-B412-40BB-880F-468725DA3843}.Debug|Any CPU.Build.0 = Debug|Any CPU {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.ActiveCfg = Release|Any CPU {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.Build.0 = Release|Any CPU + {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -169,6 +175,7 @@ Global {F91D9E0C-F235-44E1-A1DB-1213AF9663AB} = {39445712-FE9F-4406-A103-F181E9DC2233} {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B} = {03B8AB6F-9686-44AF-9AF1-6DCC6E742808} {22AC790B-B412-40BB-880F-468725DA3843} = {39445712-FE9F-4406-A103-F181E9DC2233} + {2D30E62C-6D5A-4D77-BF2B-A477B799F338} = {03B8AB6F-9686-44AF-9AF1-6DCC6E742808} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F3EFB0EB-BFFA-4C16-B235-B121695229EF} diff --git a/Core3WebApi/CodeGen.json b/Core3WebApi/CodeGen.json index d52bb08..a3f9ceb 100644 --- a/Core3WebApi/CodeGen.json +++ b/Core3WebApi/CodeGen.json @@ -1,9 +1,10 @@ { "ApiSelections": { "ExcludedControllerNames": [ + "DemoWebApi.Controllers.Polymorphism" ], - "DataModelAssemblyNames": [ "DemoWebApi.DemoDataCore", "Fonlow.WebApp.Accounts", "Core3WebApi", "Fonlow.AspNetCore.Identity" ], - "CherryPickingMethods": 32 + "DataModelAssemblyNames": [ "DemoWebApi.DemoDataCore", "Fonlow.WebApp.Accounts", "Fonlow.AspNetCore.Identity", "Core3WebApi" ], + "CherryPickingMethods": 3 }, "ClientApiOutputs": { @@ -15,6 +16,9 @@ "DataAnnotationsEnabled": true, "DataAnnotationsToComments": true, "HandleHttpRequestHeaders": true, + "UseSystemTextJson": true, + "DecorateDataModelWithDataContract": true, + "DataContractNamespace": "http://demoapp.client/2024", "Plugins": [ { diff --git a/Core3WebApi/Controllers/AuthController.cs b/Core3WebApi/Controllers/AuthController.cs index 22f1ab3..a004196 100644 --- a/Core3WebApi/Controllers/AuthController.cs +++ b/Core3WebApi/Controllers/AuthController.cs @@ -1,5 +1,4 @@ using Fonlow.AspNetCore.Identity; -using Fonlow.AspNetCore.OAuth2; using Fonlow.WebApp.Accounts; using Fonlow.WebApp.Identity; using Microsoft.AspNetCore.Authorization; @@ -14,7 +13,7 @@ using System.Security.Claims; using System.Threading.Tasks; using WebApp.Utilities; - +using Fonlow.Auth.Models; namespace WebApp.Controllers { diff --git a/Core3WebApi/Controllers/PolymorphismController.cs b/Core3WebApi/Controllers/PolymorphismController.cs new file mode 100644 index 0000000..df775b0 --- /dev/null +++ b/Core3WebApi/Controllers/PolymorphismController.cs @@ -0,0 +1,92 @@ +using Fonlow.Auth.Models; +using Microsoft.AspNetCore.Mvc; +using System.Threading.Tasks; +using System; + +namespace DemoWebApi.Controllers +{ + /// + /// For testing different commbinations of parameters and returns + /// + [Route("api/[controller]")] + public class PolymorphismController : ControllerBase + { + [HttpPost] + [Consumes("application/x-www-form-urlencoded")] //need explicit declaration for sharing endpoint + public async Task PostTokenRequestAsFormData([FromForm] RequestBase model) + { + if (model.GrantType == "password" && model is ROPCRequst) + { + return new AccessTokenResponse + { + TokenType = "bearer", + AccessToken = "AccessTokenString", + ExpiresIn = 100, + RefreshToken = "RefreshTokenString", + Scope = "some scope" + }; + } + else if (model.GrantType == "refresh_token" && model is RefreshAccessTokenRequest) + { + return new AccessTokenResponse + { + TokenType = "bearer", + AccessToken = "NewAccessTokenString", + ExpiresIn = 100, + RefreshToken = "NewRefreshTokenString", + Scope = "some scope" + }; + } + + throw new NotSupportedException(); + } + + //[HttpPost] + //[Consumes("application/json")] //need explicit declaration for sharing endpoint + //public async Task PostTokenRequest([FromBody] RequestBase model) + //{ + // if (model.GrantType == "password" && model is ROPCRequst) + // { + // return new AccessTokenResponse + // { + // TokenType = "bearer", + // AccessToken = "AccessTokenString", + // ExpiresIn = 100, + // RefreshToken = "RefreshTokenString", + // Scope = "some scope" + // }; + // } + + // throw new NotSupportedException(); + //} + + //[HttpPost] + //[Route("PostRequestBase")] + //public async Task PostRequestBase([FromBody] RequestBase model) + //{ + // return model; + //} + + //[HttpPost] + //[Route("PostROPCRequst")] + //public async Task PostROPCRequst([FromBody] ROPCRequst model) + //{ + // return model; + //} + + //[HttpPost] + //[Route("PostROPCRequst2")] + //public async Task PostROPCRequst2([FromBody] ROPCRequst model) + //{ + // return model; + //} + + //[HttpPost] + //[Route("PostROPCRequst3")] + //public async Task PostROPCRequst3([FromBody] RequestBase model) + //{ + // return model as ROPCRequst; + //} + + } +} diff --git a/Core3WebApi/Core3WebApi.csproj b/Core3WebApi/Core3WebApi.csproj index a4f9a16..e685f5e 100644 --- a/Core3WebApi/Core3WebApi.csproj +++ b/Core3WebApi/Core3WebApi.csproj @@ -11,7 +11,7 @@ - + @@ -22,6 +22,7 @@ + diff --git a/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs b/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs new file mode 100644 index 0000000..88452fc --- /dev/null +++ b/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs @@ -0,0 +1,91 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; +using System.Collections.Generic; +using System; +using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; +using System.Threading.Tasks; +using DemoWebApi.Models; +using Fonlow.Auth.Models; + +namespace WebApp.Utilities +{ + public class OAuth2RequestBinderProvider : Microsoft.AspNetCore.Mvc.ModelBinding.IModelBinderProvider + { + public IModelBinder GetBinder(ModelBinderProviderContext context) + { + if (context.Metadata.ModelType != typeof(RequestBase)) + { + return null; + } + + var subclasses = new[] { typeof(ROPCRequst), typeof(RefreshAccessTokenRequest), }; + + var binders = new Dictionary(); + foreach (var type in subclasses) + { + var modelMetadata = context.MetadataProvider.GetMetadataForType(type); + binders[type] = (modelMetadata, context.CreateBinder(modelMetadata)); + } + + return new RequestModelBinder(binders); + } + } + + public class RequestModelBinder : IModelBinder + { + private Dictionary binders; + + public RequestModelBinder(Dictionary binders) + { + this.binders = binders; + } + + public async Task BindModelAsync(ModelBindingContext bindingContext) + { + if (bindingContext.HttpContext.Request.ContentType.Contains("application/json")) + { + return; + } + //using var sr = new StreamReader(bindingContext.HttpContext.Request.Body); + //var json = await sr.ReadToEndAsync(); //only work for Json payload + + var modelKindName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "grant_type"); //todo: extract JsonPropertyName value or NewtonsoSoft JsonPropery value + var modelTypeValue = bindingContext.ValueProvider.GetValue(modelKindName).FirstValue; + + IModelBinder modelBinder; + ModelMetadata modelMetadata; + if (modelTypeValue == "password") + { + (modelMetadata, modelBinder) = binders[typeof(ROPCRequst)]; + } + else if (modelTypeValue == "refresh_token") + { + (modelMetadata, modelBinder) = binders[typeof(RefreshAccessTokenRequest)]; + } + else + { + bindingContext.Result = ModelBindingResult.Failed(); + return; + } + + var newBindingContext = DefaultModelBindingContext.CreateBindingContext( + bindingContext.ActionContext, + bindingContext.ValueProvider, + modelMetadata, + bindingInfo: null, + bindingContext.ModelName); + + await modelBinder.BindModelAsync(newBindingContext); + bindingContext.Result = newBindingContext.Result; + + if (newBindingContext.Result.IsModelSet) + { + (newBindingContext.Result.Model as RequestBase).GrantType = modelTypeValue; + // Setting the ValidationState ensures properties on derived types are correctly + bindingContext.ValidationState[newBindingContext.Result.Model] = new ValidationStateEntry + { + Metadata = modelMetadata, + }; + } + } + } +} \ No newline at end of file diff --git a/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj b/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj index afa2140..da11cea 100644 --- a/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj +++ b/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj @@ -5,8 +5,11 @@ - + + + + diff --git a/CoreWebApi.ClientApi/PolymorphismClient.cs b/CoreWebApi.ClientApi/PolymorphismClient.cs new file mode 100644 index 0000000..a1931da --- /dev/null +++ b/CoreWebApi.ClientApi/PolymorphismClient.cs @@ -0,0 +1,305 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using Fonlow.Net.Http; + +namespace DemoCoreWeb.ClientApiTextJson +{ + public partial class PolymorphismClient + { + + private System.Net.Http.HttpClient client; + + private JsonSerializerOptions jsonSerializerSettings; + + public PolymorphismClient(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings = null) + { + if (client == null) + throw new ArgumentNullException(nameof(client), "Null HttpClient."); + + if (client.BaseAddress == null) + throw new ArgumentNullException(nameof(client), "HttpClient has no BaseAddress"); + + this.client = client; + this.jsonSerializerSettings = jsonSerializerSettings; + } + + public async Task PostRopcTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var pairs = new KeyValuePair[] + { + new KeyValuePair( "grant_type", model.GrantType ), + new KeyValuePair( "username", model.Username ), + new KeyValuePair ( "password", model.Password ) + }; + var content = new FormUrlEncodedContent(pairs); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + public async Task PostRefreshTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.RefreshAccessTokenRequest model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var pairs = new KeyValuePair[] + { + new KeyValuePair( "grant_type", model.GrantType ), + new KeyValuePair( "RefreshTokenString", model.RefreshToken ), + new KeyValuePair ( "something", model.Scope ) + }; + var content = new FormUrlEncodedContent(pairs); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst + /// + public async Task PostROPCRequstToAuthAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + + + /// + /// POST api/Polymorphism/PostRequestBase + /// + public async Task PostRequestBaseAsync(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostRequestBase"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostRequestBase + /// + public Fonlow.Auth.Models.RequestBase PostRequestBase(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostRequestBase"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = client.Send(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = responseMessage.Content.ReadAsStream(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst + /// + public async Task PostROPCRequstAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst + /// + public Fonlow.Auth.Models.ROPCRequst PostROPCRequst(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = client.Send(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = responseMessage.Content.ReadAsStream(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst2 + /// + public async Task PostROPCRequst2Async(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst2"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst2 + /// + public Fonlow.Auth.Models.RequestBase PostROPCRequst2(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst2"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = client.Send(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = responseMessage.Content.ReadAsStream(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst3 + /// + public async Task PostROPCRequst3Async(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst3"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = await client.SendAsync(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + /// + /// POST api/Polymorphism/PostROPCRequst3 + /// + public Fonlow.Auth.Models.ROPCRequst PostROPCRequst3(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) + { + var requestUri = "api/Polymorphism/PostROPCRequst3"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + var responseMessage = client.Send(httpRequestMessage); + try + { + responseMessage.EnsureSuccessStatusCodeEx(); + if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } + var stream = responseMessage.Content.ReadAsStream(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + finally + { + responseMessage.Dispose(); + } + } + + } + +} diff --git a/CoreWebApi.ClientApi/WebApiClientAuto.cs b/CoreWebApi.ClientApi/WebApiClientAuto.cs index 440b305..e1dab24 100644 --- a/CoreWebApi.ClientApi/WebApiClientAuto.cs +++ b/CoreWebApi.ClientApi/WebApiClientAuto.cs @@ -14,15 +14,22 @@ namespace DemoWebApi.Controllers.Client using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; - using Newtonsoft.Json; + using System.Text.Json; + using System.Text.Json.Serialization; using Fonlow.Net.Http; + /// + /// Complex hero type + /// + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public class Hero : object { + [System.Runtime.Serialization.DataMember()] public long Id { get; set; } + [System.Runtime.Serialization.DataMember()] public string Name { get; set; } } @@ -35,9 +42,9 @@ public partial class Account private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Account(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Account(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -87,8 +94,7 @@ public async Task AdminRemoverRefreshTokensOfUsersAsync(string username, Ac { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -110,8 +116,7 @@ public int AdminRemoverRefreshTokensOfUsers(string username, Action(stream, jsonSerializerSettings); } finally { @@ -126,10 +131,7 @@ public int AdminRemoverRefreshTokensOfUsers(string username, Action GetAllRoleNamesAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -235,9 +226,7 @@ public string[] GetAllRoleNames(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -258,9 +247,7 @@ public string[] GetAllRoleNames(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -281,9 +268,7 @@ public System.Guid GetUserIdByEmail(string email, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -304,9 +289,7 @@ public System.Guid GetUserIdByEmail(string email, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -327,9 +310,7 @@ public System.Guid GetUserIdByFullName(string cn, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -350,9 +331,7 @@ public System.Guid GetUserIdByFullName(string cn, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -373,9 +352,7 @@ public System.Guid GetUserIdByUser(string username, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -399,9 +376,7 @@ public System.Guid GetUserIdByUser(string username, Action[]>(jsonReader); + return JsonSerializer.Deserialize[]>(stream, jsonSerializerSettings); } finally { @@ -425,9 +400,7 @@ public System.Guid GetUserIdByUser(string username, Action[]>(jsonReader); + return JsonSerializer.Deserialize[]>(stream, jsonSerializerSettings); } finally { @@ -451,9 +424,7 @@ public System.Guid GetUserIdByUser(string username, Action[]>(jsonReader); + return JsonSerializer.Deserialize[]>(stream, jsonSerializerSettings); } finally { @@ -477,9 +448,7 @@ public System.Guid GetUserIdByUser(string username, Action[]>(jsonReader); + return JsonSerializer.Deserialize[]>(stream, jsonSerializerSettings); } finally { @@ -502,9 +471,7 @@ public System.Guid GetUserIdByUser(string username, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -527,9 +494,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -553,9 +518,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -579,9 +542,7 @@ public Fonlow.WebApp.Accounts.Client.UserInfoViewModel GetUserInfo(System.Guid i responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -622,10 +583,7 @@ public System.Net.Http.HttpResponseMessage Logout(System.Guid connectionId, Acti { var requestUri = "api/Account/Register"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -633,9 +591,7 @@ public System.Net.Http.HttpResponseMessage Logout(System.Guid connectionId, Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -652,10 +608,7 @@ public System.Guid Register(Fonlow.WebApp.Accounts.Client.RegisterBindingModel m { var requestUri = "api/Account/Register"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -663,9 +616,7 @@ public System.Guid Register(Fonlow.WebApp.Accounts.Client.RegisterBindingModel m { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -688,8 +639,7 @@ public async Task RemoveOldUserTokensAsync(System.DateTime pastDateUtc, Act { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -712,8 +662,7 @@ public int RemoveOldUserTokens(System.DateTime pastDateUtc, Action(stream, jsonSerializerSettings); } finally { @@ -735,8 +684,7 @@ public async Task RemoveRefreshTokensOfUserAsync(Action(stream, jsonSerializerSettings); } finally { @@ -758,8 +706,7 @@ public int RemoveRefreshTokensOfUser(Action(stream, jsonSerializerSettings); } finally { @@ -828,10 +775,7 @@ public System.Net.Http.HttpResponseMessage RemoveUser(System.Guid userId, Action { var requestUri = "api/Account/ResetPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -846,10 +790,7 @@ public System.Net.Http.HttpResponseMessage ResetPassword(Fonlow.WebApp.Accounts. { var requestUri = "api/Account/ResetPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -864,10 +805,7 @@ public System.Net.Http.HttpResponseMessage ResetPassword(Fonlow.WebApp.Accounts. { var requestUri = "api/Account/SetPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -882,10 +820,7 @@ public System.Net.Http.HttpResponseMessage SetPassword(Fonlow.WebApp.Accounts.Cl { var requestUri = "api/Account/SetPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -902,10 +837,7 @@ public System.Net.Http.HttpResponseMessage SetPassword(Fonlow.WebApp.Accounts.Cl { var requestUri = "api/Account/SetUserPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -922,10 +854,7 @@ public System.Net.Http.HttpResponseMessage SetUserPassword(Fonlow.WebApp.Account { var requestUri = "api/Account/SetUserPassword"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -943,9 +872,9 @@ public partial class DateTypes private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public DateTypes(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -970,9 +899,7 @@ public DateTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonS { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -993,9 +920,7 @@ public System.DateOnly GetDateOnly(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1017,9 +942,7 @@ public System.DateOnly GetDateOnly(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1041,9 +964,7 @@ public System.DateOnly GetDateOnly(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1065,9 +986,7 @@ public System.DateOnly GetDateOnly(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1089,9 +1008,7 @@ public System.DateTimeOffset GetDateTimeOffset(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1112,9 +1029,7 @@ public System.DateTimeOffset GetDateTimeOffset(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1135,9 +1050,7 @@ public System.DateTimeOffset GetNextHour(System.DateTimeOffset dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1159,9 +1072,7 @@ public System.DateTimeOffset GetNextHour(System.DateTimeOffset dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1183,9 +1094,7 @@ public System.DateTimeOffset GetNextHourNullable(int n, System.Nullable(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1206,9 +1115,7 @@ public System.DateTimeOffset GetNextHourNullable(int n, System.Nullable(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1229,9 +1136,7 @@ public System.DateTime GetNextYear(System.DateTime dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1253,9 +1158,7 @@ public System.DateTime GetNextYear(System.DateTime dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1277,9 +1180,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1295,10 +1196,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1325,10 +1221,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1354,10 +1245,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1383,10 +1269,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1412,10 +1293,7 @@ public System.DateTime GetNextYearNullable(int n, System.Nullable(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1440,10 +1316,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1468,10 +1339,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1497,10 +1363,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1526,10 +1387,7 @@ public System.DateOnly PostDateOnly(System.DateOnly d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1554,10 +1410,7 @@ public System.DateTime PostDateTime(System.DateTime d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1583,10 +1434,7 @@ public System.DateTime PostDateTime(System.DateTime d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1612,10 +1458,7 @@ public System.DateTimeOffset PostDateTimeOffset(System.DateTimeOffset d, Action< { var requestUri = "api/DateTypes/ForDateTimeOffset"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1623,9 +1466,7 @@ public System.DateTimeOffset PostDateTimeOffset(System.DateTimeOffset d, Action< { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1641,10 +1482,7 @@ public async Task PostDateTimeOffsetForOAsync(System.DateTimeOffset d, A { var requestUri = "api/DateTypes/ForDateTimeOffsetForO"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1670,10 +1508,7 @@ public string PostDateTimeOffsetForO(System.DateTimeOffset d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1726,10 +1556,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { var requestUri = "api/DateTypes/ForDateTimeOffsetForOffset"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1737,9 +1564,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1755,10 +1580,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { var requestUri = "api/DateTypes/DateTimeOffsetNullable"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1767,9 +1589,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1785,10 +1605,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { var requestUri = "api/DateTypes/DateTimeOffsetNullable"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -1797,9 +1614,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -1814,10 +1629,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { var requestUri = "api/DateTypes/ForDateTimeOffsetStringForOffset"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -1825,9 +1637,7 @@ public System.TimeSpan PostDateTimeOffsetForOffset(System.DateTimeOffset d, Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1842,10 +1652,7 @@ public System.TimeSpan PostDateTimeOffsetStringForOffset(string s, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1870,10 +1675,7 @@ public System.TimeSpan PostDateTimeOffsetStringForOffset(string s, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1898,10 +1698,7 @@ public System.DateTime PostNextYear(System.DateTime dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1932,9 +1727,7 @@ public System.DateTime PostNextYear(System.DateTime dt, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1955,9 +1748,7 @@ public System.DateOnly QueryDateOnlyAsString(string d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -1978,9 +1769,7 @@ public System.DateOnly QueryDateOnlyAsString(string d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2001,9 +1790,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2028,9 +1815,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -2055,9 +1840,7 @@ public System.DateTimeOffset RouteDateTimeOffset(System.DateTimeOffset d, Action responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -2074,9 +1857,9 @@ public partial class Entities private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Entities(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -2095,10 +1878,7 @@ public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSe { var requestUri = "api/Entities/createCompany"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2107,9 +1887,7 @@ public Entities(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSe responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2124,10 +1902,7 @@ public DemoWebApi.DemoData.Client.Company CreateCompany(DemoWebApi.DemoData.Clie { var requestUri = "api/Entities/createCompany"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2136,9 +1911,7 @@ public DemoWebApi.DemoData.Client.Company CreateCompany(DemoWebApi.DemoData.Clie responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2153,10 +1926,7 @@ public async Task CreatePersonAsync(DemoWebApi.DemoData.Client.Person p, A { var requestUri = "api/Entities/createPerson"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2164,8 +1934,7 @@ public async Task CreatePersonAsync(DemoWebApi.DemoData.Client.Person p, A { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int64.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2180,10 +1949,7 @@ public long CreatePerson(DemoWebApi.DemoData.Client.Person p, Action(stream, jsonSerializerSettings); } finally { @@ -2207,10 +1972,7 @@ public long CreatePerson(DemoWebApi.DemoData.Client.Person p, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2236,10 +1996,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien { var requestUri = "api/Entities/createPerson2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2248,9 +2005,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2265,10 +2020,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien { var requestUri = "api/Entities/createPerson3"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2277,9 +2029,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson2(DemoWebApi.DemoData.Clien responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2294,10 +2044,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson3(DemoWebApi.DemoData.Clien { var requestUri = "api/Entities/createPerson3"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2306,9 +2053,7 @@ public DemoWebApi.DemoData.Client.Person CreatePerson3(DemoWebApi.DemoData.Clien responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2368,9 +2113,7 @@ public void Delete(long id, Action h responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2392,9 +2135,7 @@ public DemoWebApi.DemoData.Client.Company GetCompany(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2409,10 +2150,7 @@ public DemoWebApi.DemoData.Client.Company GetCompany(long id, Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2438,10 +2174,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData { var requestUri = "api/Entities/Mims"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, p); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(p, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2450,9 +2183,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2467,10 +2198,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData { var requestUri = "api/Entities/MyGeneric"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2479,9 +2207,7 @@ public DemoWebApi.DemoData.Client.MimsResult GetMims(DemoWebApi.DemoData responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2496,10 +2222,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri { var requestUri = "api/Entities/MyGeneric"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2508,9 +2231,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2525,10 +2246,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri { var requestUri = "api/Entities/MyGenericPerson"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2537,9 +2255,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2554,10 +2270,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri { var requestUri = "api/Entities/MyGenericPerson"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2566,9 +2279,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -2594,9 +2305,7 @@ public DemoWebApi.DemoData.Client.MyGeneric GetMyGeneri responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2622,9 +2331,7 @@ public DemoWebApi.DemoData.Client.Person GetPerson(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2646,9 +2353,7 @@ public DemoWebApi.DemoData.Client.Person GetPerson(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2670,9 +2375,7 @@ public DemoWebApi.DemoData.Client.Person GetPerson2(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2687,10 +2390,7 @@ public async Task LinkPersonAsync(long id, string relationship, DemoWebApi { var requestUri = "api/Entities/link?id="+id+"&relationship="+(relationship == null ? "" : Uri.EscapeDataString(relationship)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, person); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(person, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2698,8 +2398,7 @@ public async Task LinkPersonAsync(long id, string relationship, DemoWebApi { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Boolean.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2714,10 +2413,7 @@ public bool LinkPerson(long id, string relationship, DemoWebApi.DemoData.Client. { var requestUri = "api/Entities/link?id="+id+"&relationship="+(relationship == null ? "" : Uri.EscapeDataString(relationship)); using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, person); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(person, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2725,8 +2421,7 @@ public bool LinkPerson(long id, string relationship, DemoWebApi.DemoData.Client. { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Boolean.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2741,10 +2436,7 @@ public async Task PatchPersonAsync(DemoWebApi.DemoData.Client.Person per { var requestUri = "api/Entities/patchPerson"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Patch, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, person); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(person, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2769,10 +2461,7 @@ public string PatchPerson(DemoWebApi.DemoData.Client.Person person, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2826,10 +2510,7 @@ public DemoWebApi.DemoData.Client.IdMap PostIdMap(DemoWebApi.DemoData.Client.IdM { var requestUri = "api/Entities/IdMap"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, idMap); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(idMap, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -2838,9 +2519,7 @@ public DemoWebApi.DemoData.Client.IdMap PostIdMap(DemoWebApi.DemoData.Client.IdM responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -2855,10 +2534,7 @@ public async Task UpdatePersonAsync(DemoWebApi.DemoData.Client.Person pe { var requestUri = "api/Entities/updatePerson"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, person); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(person, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -2883,10 +2559,7 @@ public string UpdatePerson(DemoWebApi.DemoData.Client.Person person, Action h { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3002,9 +2673,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetAsyncHeroes(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3027,9 +2696,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetAsyncHeroes(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3052,9 +2719,7 @@ public DemoWebApi.Controllers.Client.Hero GetHero(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3077,9 +2742,7 @@ public DemoWebApi.Controllers.Client.Hero GetHero(long id, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3102,9 +2765,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetHeros(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3119,10 +2780,7 @@ public DemoWebApi.Controllers.Client.Hero[] GetHeros(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3148,10 +2804,7 @@ public DemoWebApi.Controllers.Client.Hero Post(string name, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3184,9 +2835,7 @@ public DemoWebApi.Controllers.Client.Hero Post(string name, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3208,9 +2857,7 @@ public DemoWebApi.Controllers.Client.Hero PostWithQuery(string name, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3226,10 +2873,7 @@ public DemoWebApi.Controllers.Client.Hero PostWithQuery(string name, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3256,10 +2898,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero { var requestUri = "api/Heroes"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, hero); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(hero, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3268,9 +2907,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3295,9 +2932,7 @@ public DemoWebApi.Controllers.Client.Hero Put(DemoWebApi.Controllers.Client.Hero responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3322,9 +2957,7 @@ public DemoWebApi.Controllers.Client.Hero[] Search(string name, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3338,9 +2971,9 @@ public partial class Home private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Home(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Home(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -3384,9 +3017,9 @@ public partial class Polymorphism private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Polymorphism(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Polymorphism(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -3405,10 +3038,7 @@ public Polymorphism(System.Net.Http.HttpClient client, JsonSerializerSettings js { var requestUri = "api/Polymorphism"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -3417,9 +3047,7 @@ public Polymorphism(System.Net.Http.HttpClient client, JsonSerializerSettings js responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3434,10 +3062,7 @@ public Fonlow.AspNetCore.OAuth2.Client.RequestBase Authenticate(Fonlow.AspNetCor { var requestUri = "api/Polymorphism"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, model); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -3446,9 +3071,7 @@ public Fonlow.AspNetCore.OAuth2.Client.RequestBase Authenticate(Fonlow.AspNetCor responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3466,9 +3089,9 @@ public partial class SuperDemo private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public SuperDemo(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public SuperDemo(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -3639,8 +3262,7 @@ public async Task GetBoolAsync(Action(stream, jsonSerializerSettings); } finally { @@ -3661,8 +3283,7 @@ public bool GetBool(Action handleHea { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Boolean.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3683,8 +3304,7 @@ public async Task GetbyteAsync(Action(stream, jsonSerializerSettings); } finally { @@ -3705,8 +3325,7 @@ public byte Getbyte(Action handleHea { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Byte.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3728,9 +3347,7 @@ public async Task GetByteArrayAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3752,9 +3369,7 @@ public byte[] GetByteArray(Action ha responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3775,9 +3390,7 @@ public async Task GetCharAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3798,9 +3411,7 @@ public char GetChar(Action handleHea { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3822,9 +3433,7 @@ public char GetChar(Action handleHea responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3846,9 +3455,7 @@ public DemoWebApi.DemoData.Client.Person[] GetCollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3869,9 +3476,7 @@ public DemoWebApi.DemoData.Client.Person[] GetCollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3892,9 +3497,7 @@ public DemoWebApi.DemoData.Client.Days GetDay(DemoWebApi.DemoData.Client.Days d, { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3915,9 +3518,7 @@ public async Task GetDecimalAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3938,9 +3539,7 @@ public decimal GetDecimal(Action han { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3962,9 +3561,7 @@ public async Task GetDecimalArrayQAsync(decimal[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -3986,9 +3583,7 @@ public decimal[] GetDecimalArrayQ(decimal[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4009,9 +3604,7 @@ public async Task GetDecimalSquareAsync(decimal d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4032,9 +3625,7 @@ public decimal GetDecimalSquare(decimal d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4055,9 +3646,7 @@ public async Task GetDecimalZeroAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4078,9 +3667,7 @@ public decimal GetDecimalZero(Action { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4101,9 +3688,7 @@ public decimal GetDecimalZero(Action { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4124,9 +3709,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4147,9 +3730,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4170,9 +3751,7 @@ public System.Collections.Generic.IDictionary GetDictionary(Acti { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4193,8 +3772,7 @@ public async Task GetdoubleAsync(Action(stream, jsonSerializerSettings); } finally { @@ -4215,8 +3793,7 @@ public double Getdouble(Action handl { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Double.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4238,8 +3815,7 @@ public async Task GetDoubleZeroAsync(Action(stream, jsonSerializerSettings); } finally { @@ -4261,8 +3837,7 @@ public double GetDoubleZero(Action h { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Double.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4330,9 +3905,7 @@ public string GetEmptyString(Action responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4354,9 +3927,7 @@ public DemoWebApi.DemoData.Client.Days[] GetEnumArrayDays(DemoWebApi.DemoData.Cl responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4378,9 +3949,7 @@ public DemoWebApi.DemoData.Client.Days[] GetEnumArrayDays(DemoWebApi.DemoData.Cl responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4402,9 +3971,7 @@ public System.DayOfWeek[] GetEnumArrayQ2(System.DayOfWeek[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4425,8 +3992,7 @@ public async Task GetFloatZeroAsync(Action(stream, jsonSerializerSettings); } finally { @@ -4447,8 +4013,7 @@ public float GetFloatZero(Action han { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Single.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4469,9 +4034,7 @@ public float GetFloatZero(Action han { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4492,9 +4055,7 @@ public DemoWebApi.DemoData.Client.Person[] GetICollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4515,9 +4076,7 @@ public DemoWebApi.DemoData.Client.Person[] GetICollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4538,9 +4097,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIList(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4562,9 +4119,7 @@ public async Task GetInt2DAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4586,9 +4141,7 @@ public async Task GetInt2DAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4610,9 +4163,7 @@ public async Task GetInt2DJaggedAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4634,9 +4185,7 @@ public int[][] GetInt2DJagged(Action responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4658,9 +4207,7 @@ public async Task GetIntArrayAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4682,9 +4229,7 @@ public int[] GetIntArray(Action hand responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4706,9 +4251,7 @@ public async Task GetIntArrayQAsync(int[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4730,9 +4273,7 @@ public int[] GetIntArrayQ(int[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4754,9 +4295,7 @@ public async Task GetIntArrayQ2Async(long[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4778,9 +4317,7 @@ public long[] GetIntArrayQ2(long[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4801,8 +4338,7 @@ public async Task GetIntSquareAsync(int d, Action(stream, jsonSerializerSettings); } finally { @@ -4823,8 +4359,7 @@ public int GetIntSquare(int d, Action(stream, jsonSerializerSettings); } finally { @@ -4845,9 +4380,7 @@ public int GetIntSquare(int d, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4868,9 +4401,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyCollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4891,9 +4422,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyCollection(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4914,9 +4443,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -4937,9 +4464,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4960,9 +4485,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -4984,9 +4507,7 @@ public DemoWebApi.DemoData.Client.Person[] GetIReadOnlyList(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5008,9 +4529,7 @@ public DemoWebApi.DemoData.Client.Person[] GetList(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5032,9 +4551,7 @@ public DemoWebApi.DemoData.Client.Person[] GetList(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -5056,9 +4573,7 @@ public System.Nullable GetNullableDecimal(bool hasValue, Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -5080,9 +4595,7 @@ public System.Nullable GetNullableDecimal(bool hasValue, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5104,9 +4617,7 @@ public DemoWebApi.DemoData.Client.Person GetNullPerson(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5174,9 +4685,7 @@ public string GetNullString(Action h responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -5198,9 +4707,7 @@ public string GetNullString(Action h responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -5222,9 +4729,7 @@ public string GetNullString(Action h responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -5246,9 +4751,7 @@ public string GetNullString(Action h responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize, System.Nullable>>(jsonReader); + return JsonSerializer.Deserialize, System.Nullable>>(stream, jsonSerializerSettings); } finally { @@ -5269,8 +4772,7 @@ public async Task GetsbyteAsync(Action(stream, jsonSerializerSettings); } finally { @@ -5291,8 +4793,7 @@ public sbyte Getsbyte(Action handleH { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.SByte.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5313,8 +4814,7 @@ public async Task GetShortAsync(Action(stream, jsonSerializerSettings); } finally { @@ -5335,8 +4835,7 @@ public short GetShort(Action handleH { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int16.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5358,9 +4857,7 @@ public async Task GetStringArrayQAsync(string[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5382,9 +4879,7 @@ public string[] GetStringArrayQ(string[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5406,9 +4901,7 @@ public async Task GetStringArrayQ2Async(string[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5430,9 +4923,7 @@ public string[] GetStringArrayQ2(string[] a, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5479,8 +4970,7 @@ public async Task GetUintAsync(Action(stream, jsonSerializerSettings); } finally { @@ -5501,8 +4991,7 @@ public uint GetUint(Action handleHea { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.UInt32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5523,8 +5012,7 @@ public async Task GetulongAsync(Action(stream, jsonSerializerSettings); } finally { @@ -5545,8 +5033,7 @@ public ulong Getulong(Action handleH { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.UInt64.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5567,8 +5054,7 @@ public async Task GetUShortAsync(Action(stream, jsonSerializerSettings); } finally { @@ -5589,8 +5075,7 @@ public ushort GetUShort(Action handl { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.UInt16.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5629,10 +5114,7 @@ public System.Net.Http.HttpResponseMessage PostActionResult(Action PostCollectionAsync(DemoWebApi.DemoData.Client.Person[] l { var requestUri = "api/SuperDemo/Collection"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5712,8 +5182,7 @@ public async Task PostCollectionAsync(DemoWebApi.DemoData.Client.Person[] l { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5728,10 +5197,7 @@ public int PostCollection(DemoWebApi.DemoData.Client.Person[] list, Action(stream, jsonSerializerSettings); } finally { @@ -5755,10 +5220,7 @@ public int PostCollection(DemoWebApi.DemoData.Client.Person[] list, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5784,10 +5244,7 @@ public DemoWebApi.DemoData.Client.Days[] PostDay(DemoWebApi.DemoData.Client.Days { var requestUri = "api/SuperDemo/enumPost?d="+d; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d2); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d2, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -5796,9 +5253,7 @@ public DemoWebApi.DemoData.Client.Days[] PostDay(DemoWebApi.DemoData.Client.Days responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5813,10 +5268,7 @@ public async Task PostDictionaryAsync(System.Collections.Generic.IDictionar { var requestUri = "api/SuperDemo/StringPersonDic"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, dic); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(dic, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5824,8 +5276,7 @@ public async Task PostDictionaryAsync(System.Collections.Generic.IDictionar { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5840,10 +5291,7 @@ public int PostDictionary(System.Collections.Generic.IDictionary(stream, jsonSerializerSettings); } finally { @@ -5867,10 +5314,7 @@ public int PostDictionary(System.Collections.Generic.IDictionary(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5896,10 +5338,7 @@ public System.Guid[] PostGuids(System.Guid[] guids, Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5925,10 +5362,7 @@ public async Task PostICollectionAsync(DemoWebApi.DemoData.Client.Person[] { var requestUri = "api/SuperDemo/ICollection"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5936,8 +5370,7 @@ public async Task PostICollectionAsync(DemoWebApi.DemoData.Client.Person[] { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -5952,10 +5385,7 @@ public int PostICollection(DemoWebApi.DemoData.Client.Person[] list, Action(stream, jsonSerializerSettings); } finally { @@ -5979,10 +5408,7 @@ public async Task PostIListAsync(DemoWebApi.DemoData.Client.Person[] list, { var requestUri = "api/SuperDemo/IList"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -5990,8 +5416,7 @@ public async Task PostIListAsync(DemoWebApi.DemoData.Client.Person[] list, { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6006,10 +5431,7 @@ public int PostIList(DemoWebApi.DemoData.Client.Person[] list, Action(stream, jsonSerializerSettings); } finally { @@ -6033,10 +5454,7 @@ public async Task PostInt2DAsync(int[,] a, Action PostInt2DAsync(int[,] a, Action(stream, jsonSerializerSettings); } finally { @@ -6060,10 +5477,7 @@ public bool PostInt2D(int[,] a, Action(stream, jsonSerializerSettings); } finally { @@ -6087,10 +5500,7 @@ public async Task PostInt2DJaggedAsync(int[][] a, Action PostInt2DJaggedAsync(int[][] a, Action(stream, jsonSerializerSettings); } finally { @@ -6114,10 +5523,7 @@ public bool PostInt2DJagged(int[][] a, Action(stream, jsonSerializerSettings); } finally { @@ -6141,10 +5546,7 @@ public async Task PostIntArrayAsync(int[] a, Action PostIntArrayAsync(int[] a, Action(stream, jsonSerializerSettings); } finally { @@ -6168,10 +5569,7 @@ public bool PostIntArray(int[] a, Action(stream, jsonSerializerSettings); } finally { @@ -6195,10 +5592,7 @@ public async Task PostIReadOnlyCollectionAsync(DemoWebApi.DemoData.Client.P { var requestUri = "api/SuperDemo/IReadOnlyCollection"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -6206,8 +5600,7 @@ public async Task PostIReadOnlyCollectionAsync(DemoWebApi.DemoData.Client.P { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6222,10 +5615,7 @@ public int PostIReadOnlyCollection(DemoWebApi.DemoData.Client.Person[] list, Act { var requestUri = "api/SuperDemo/IReadOnlyCollection"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -6233,8 +5623,7 @@ public int PostIReadOnlyCollection(DemoWebApi.DemoData.Client.Person[] list, Act { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6249,10 +5638,7 @@ public async Task PostIReadOnlyListAsync(DemoWebApi.DemoData.Client.Person[ { var requestUri = "api/SuperDemo/IReadOnlyList"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -6260,8 +5646,7 @@ public async Task PostIReadOnlyListAsync(DemoWebApi.DemoData.Client.Person[ { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6276,10 +5661,7 @@ public int PostIReadOnlyList(DemoWebApi.DemoData.Client.Person[] list, Action(stream, jsonSerializerSettings); } finally { @@ -6303,10 +5684,7 @@ public async Task PostListAsync(DemoWebApi.DemoData.Client.Person[] list, A { var requestUri = "api/SuperDemo/List"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, list); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(list, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -6314,8 +5692,7 @@ public async Task PostListAsync(DemoWebApi.DemoData.Client.Person[] list, A { responseMessage.EnsureSuccessStatusCodeEx(); var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - return System.Int32.Parse(jsonReader.ReadAsString()); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6330,10 +5707,7 @@ public int PostList(DemoWebApi.DemoData.Client.Person[] list, Action(stream, jsonSerializerSettings); } finally { @@ -6357,10 +5730,7 @@ public int PostList(DemoWebApi.DemoData.Client.Person[] list, Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6386,10 +5754,7 @@ public System.Tuple PostWithQueryButEmptyBody(string s, int i, Acti { var requestUri = "api/SuperDemo/PostEmpty/"+i; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, s); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(s, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -6398,9 +5763,7 @@ public System.Tuple PostWithQueryButEmptyBody(string s, int i, Acti responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6418,9 +5781,9 @@ public partial class Tuple private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Tuple(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -6439,10 +5802,7 @@ public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSeria { var requestUri = "api/Tuple/ChangeName"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, d); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(d, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -6451,9 +5811,7 @@ public Tuple(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSeria responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6468,10 +5826,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -6504,9 +5857,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6528,9 +5879,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6552,9 +5901,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6576,9 +5923,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6600,9 +5945,7 @@ public DemoWebApi.DemoData.Client.Person ChangeName(System.Tuple>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6624,9 +5967,7 @@ public System.Tuple GetTuple1(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6648,9 +5989,7 @@ public System.Tuple GetTuple1(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6672,9 +6011,7 @@ public System.Tuple GetTuple2(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6696,9 +6033,7 @@ public System.Tuple GetTuple2(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6720,9 +6055,7 @@ public System.Tuple GetTuple3(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6744,9 +6077,7 @@ public System.Tuple GetTuple3(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6768,9 +6099,7 @@ public System.Tuple GetTuple4(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6792,9 +6121,7 @@ public System.Tuple GetTuple4(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6816,9 +6143,7 @@ public System.Tuple GetTuple5(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6840,9 +6165,7 @@ public System.Tuple GetTuple5(Action>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6864,9 +6187,7 @@ public System.Tuple GetTuple6(Actio responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6888,9 +6209,7 @@ public System.Tuple GetTuple6(Actio responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6912,9 +6231,7 @@ public System.Tuple GetTuple7 responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>(jsonReader); + return JsonSerializer.Deserialize>(stream, jsonSerializerSettings); } finally { @@ -6936,9 +6253,7 @@ public System.Tuple GetTuple7 responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>>(jsonReader); + return JsonSerializer.Deserialize>>(stream, jsonSerializerSettings); } finally { @@ -6960,9 +6275,7 @@ public System.Tuple GetTuple7 responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize>>(jsonReader); + return JsonSerializer.Deserialize>>(stream, jsonSerializerSettings); } finally { @@ -6977,10 +6290,7 @@ public System.Tuple GetTuple7 { var requestUri = "api/Tuple/PeopleCompany2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, peopleAndCompany); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(peopleAndCompany, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -6989,9 +6299,7 @@ public System.Tuple GetTuple7 responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7006,10 +6314,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany2(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7035,10 +6338,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany2(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7064,10 +6362,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany3(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7093,10 +6386,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany3(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7122,10 +6410,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany4(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7151,10 +6434,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany4(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7180,10 +6458,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany5(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7209,10 +6482,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany5(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7238,10 +6506,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany6(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7267,10 +6530,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany6(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7296,10 +6554,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany7(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7325,10 +6578,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany7(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7354,10 +6602,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany8(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7383,10 +6626,7 @@ public DemoWebApi.DemoData.Client.Person LinkPeopleCompany8(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7412,10 +6650,7 @@ public DemoWebApi.DemoData.Client.Person LinkPersonCompany1(System.Tuple(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7441,10 +6674,7 @@ public async Task PostTuple1Async(System.Tuple tuple, Action PostTuple1Async(System.Tuple tuple, Action(stream, jsonSerializerSettings); } finally { @@ -7468,10 +6697,7 @@ public int PostTuple1(System.Tuple tuple, Action tuple, Action(stream, jsonSerializerSettings); } finally { @@ -7495,10 +6720,7 @@ public async Task PostTuple2Async(System.Tuple tuple, Actio { var requestUri = "api/Tuple/Tuple2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, tuple); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(tuple, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -7523,10 +6745,7 @@ public string PostTuple2(System.Tuple tuple, Action PostTuple3Async(System.Tuple tupl { var requestUri = "api/Tuple/Tuple3"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, tuple); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(tuple, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -7579,10 +6795,7 @@ public string PostTuple3(System.Tuple tuple, Action PostTuple4Async(System.Tuple tuple, Action { var requestUri = "api/Tuple/Tuple4"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, tuple); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(tuple, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -7663,10 +6870,7 @@ public async Task PostTuple5Async(System.Tuple tuple { var requestUri = "api/Tuple/Tuple5"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, tuple); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(tuple, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -7719,10 +6920,7 @@ public async Task PostTuple6Async(System.Tuple PostTuple7Async(System.Tuple PostTuple8Async(System.Tuple GetAsync(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -7976,9 +7157,7 @@ public string[] Get(Action handleHea { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8139,9 +7318,7 @@ public async Task Get2Async(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8162,9 +7339,7 @@ public string[] Get2(Action handleHe { responseMessage.EnsureSuccessStatusCodeEx(); var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8179,10 +7354,7 @@ public async Task PostAsync(string value, Action + /// 2D position + /// with X and Y + /// for Demo + /// + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public struct MyPoint { + /// + /// X + /// + [System.Runtime.Serialization.DataMember()] public double X; + /// + /// Y + /// + [System.Runtime.Serialization.DataMember()] public double Y; } } @@ -8295,195 +7472,697 @@ namespace DemoWebApi.DemoData.Client { - public class Entity : object - { - - public DemoWebApi.DemoData.Client.Address[] Addresses { get; set; } - - public System.Nullable Id { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string Name { get; set; } - - public DemoWebApi.DemoData.Client.PhoneNumber[] PhoneNumbers { get; set; } - - public System.Uri Web { get; set; } - } - + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public class Address : object { + [System.Runtime.Serialization.DataMember()] public string City { get; set; } [System.ComponentModel.DefaultValueAttribute("Australia")] + [System.Runtime.Serialization.DataMember()] public string Country { get; set; } = "Australia"; - public DemoWebApi.DemoData.Client.Entity Entity { get; set; } - - public System.Guid EntityId { get; set; } - + [System.Runtime.Serialization.DataMember()] public System.Guid Id { get; set; } + [System.Runtime.Serialization.DataMember()] public string PostalCode { get; set; } + [System.Runtime.Serialization.DataMember()] public string State { get; set; } + [System.Runtime.Serialization.DataMember()] public string Street1 { get; set; } + [System.Runtime.Serialization.DataMember()] public string Street2 { get; set; } [System.ComponentModel.DefaultValueAttribute(AddressType.Residential)] + [System.Runtime.Serialization.DataMember()] public DemoWebApi.DemoData.Client.AddressType Type { get; set; } = AddressType.Residential; + /// + /// It is a field + /// + [System.Runtime.Serialization.DataMember()] public DemoWebApi.DemoData.Another.Client.MyPoint Location { get; set; } } + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public enum AddressType { + [System.Runtime.Serialization.EnumMember()] Postal, + [System.Runtime.Serialization.EnumMember()] Residential, } - public class PhoneNumber : object + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class Company : DemoWebApi.DemoData.Client.Entity { - public System.Guid EntityId { get; set; } + /// + /// BusinessNumber to be serialized as BusinessNum + /// + [System.Runtime.Serialization.DataMember(Name="BusinessNum")] + public string BusinessNumber { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string BusinessNumberType { get; set; } - public string FullNumber { get; set; } + /// + /// Data type: Date + /// + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] + [System.Runtime.Serialization.DataMember()] + public System.DateTimeOffset FoundDate { get; set; } - public System.Guid Id { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.DateOnly RegisterDate { get; set; } - public DemoWebApi.DemoData.Client.PhoneType PhoneType { get; set; } + [System.Runtime.Serialization.DataMember()] + public string[][] TextMatrix { get; set; } + + [System.Runtime.Serialization.DataMember()] + public int[,] Int2D { get; set; } + + [System.Runtime.Serialization.DataMember()] + public int[][] Int2DJagged { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string[] Lines { get; set; } } - public enum PhoneType + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public enum Days { - Tel, + [System.Runtime.Serialization.EnumMember()] + Sat = 1, - Mobile, + [System.Runtime.Serialization.EnumMember()] + Sun = 2, - Skype, + [System.Runtime.Serialization.EnumMember()] + Mon = 3, - Fax, + [System.Runtime.Serialization.EnumMember()] + Tue = 4, + + [System.Runtime.Serialization.EnumMember()] + Wed = 5, + + /// + /// Thursday + /// + [System.Runtime.Serialization.EnumMember()] + Thu = 6, + + [System.Runtime.Serialization.EnumMember()] + Fri = 7, } - public class Person : DemoWebApi.DemoData.Client.Entity + /// + /// Base class of company and person + /// + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class Entity : object { - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] - public System.Nullable Baptised { get; set; } + /// + /// Multiple addresses + /// + [System.Runtime.Serialization.DataMember()] + public DemoWebApi.DemoData.Client.Address[] Addresses { get; set; } - public System.Nullable DOB { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Nullable Id { get; set; } - public string GivenName { get; set; } + /// + /// Name of the entity. + /// Required + /// + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.Runtime.Serialization.DataMember(IsRequired =true)] + public string Name { get; set; } - public string Surname { get; set; } + [System.Runtime.Serialization.DataMember()] + public DemoWebApi.DemoData.Client.PhoneNumber[] PhoneNumbers { get; set; } + + [System.Runtime.Serialization.DataMember()] + public System.Uri Web { get; set; } } - public class Company : DemoWebApi.DemoData.Client.Entity + /// + /// To test different serializations against Guid + /// + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class IdMap : object { - public string BusinessNumber { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Guid Id { get; set; } - public string BusinessNumberType { get; set; } + [System.Runtime.Serialization.DataMember(EmitDefaultValue=false)] + public System.Guid IdNotEmitDefaultValue { get; set; } - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] - public System.DateTimeOffset FoundDate { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Nullable NullableId { get; set; } - public System.DateOnly RegisterDate { get; set; } + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.Runtime.Serialization.DataMember(IsRequired =true)] + public string RequiredName { get; set; } - public string[][] TextMatrix { get; set; } + [System.Runtime.Serialization.DataMember()] + public string Text { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public enum MedicalContraindiationResponseTypeReason + { - public int[,] Int2D { get; set; } + [System.Runtime.Serialization.EnumMember(Value="Mm")] + M, - public int[][] Int2DJagged { get; set; } + [System.Runtime.Serialization.EnumMember(Value="Ss")] + S, - public string[] Lines { get; set; } + [System.Runtime.Serialization.EnumMember(Value="Pp")] + P, + + [System.Runtime.Serialization.EnumMember(Value="I")] + I, + + [System.Runtime.Serialization.EnumMember(Value="A")] + A, } - public enum Days + [System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public enum MedicalContraindiationResponseTypeTypeCode { - Sat = 1, + [System.Runtime.Serialization.EnumMember(Value="P")] + P, - Sun = 2, + [System.Runtime.Serialization.EnumMember(Value="Tt")] + T, + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class MimsPackage : object + { - Mon = 3, + /// + /// Range: inclusive between 10 and 100 + /// + [System.ComponentModel.DefaultValueAttribute(20)] + [System.ComponentModel.DataAnnotations.Range(typeof(System.Int32), "10", "100", ErrorMessage="KK has to be between 10 and 100.")] + [System.Runtime.Serialization.DataMember()] + public int KK { get; set; } = 20; - Tue = 4, + /// + /// Having an initialized value in the property is not like defining a DefaultValueAttribute. Such intialization happens at run time, + /// and there's no reliable way for a codegen to know if the value is declared by the programmer, or is actually the natural default value like 0. + /// + [System.Runtime.Serialization.DataMember()] + public int KK2 { get; set; } - Wed = 5, + [System.Runtime.Serialization.DataMember()] + public System.Nullable OptionalEnum { get; set; } - Thu = 6, + [System.Runtime.Serialization.DataMember()] + public System.Nullable OptionalInt { get; set; } - Fri = 7, + [System.Runtime.Serialization.DataMember()] + public DemoWebApi.DemoData.Client.MimsResult Result { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Tag { get; set; } } + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public class MimsResult : object { + [System.Runtime.Serialization.DataMember()] public System.DateTime GeneratedAt { get; set; } + [System.Runtime.Serialization.DataMember()] public string Message { get; set; } + [System.Runtime.Serialization.DataMember()] public T Result { get; set; } + [System.Runtime.Serialization.DataMember()] public bool Success { get; set; } } + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public enum MyEnumType + { + + [System.Runtime.Serialization.EnumMember()] + First = 1, + + [System.Runtime.Serialization.EnumMember()] + Two = 2, + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public class MyGeneric : object { + [System.Runtime.Serialization.DataMember()] public K MyK { get; set; } + [System.Runtime.Serialization.DataMember()] public T MyT { get; set; } + [System.Runtime.Serialization.DataMember()] public U MyU { get; set; } + [System.Runtime.Serialization.DataMember()] public string Status { get; set; } } - public class IdMap : object + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class MyPeopleDic : object { - public System.Guid Id { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Collections.Generic.IDictionary AnotherDic { get; set; } - public System.Guid IdNotEmitDefaultValue { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Collections.Generic.IDictionary Dic { get; set; } - public System.Nullable NullableId { get; set; } + [System.Runtime.Serialization.DataMember()] + public System.Collections.Generic.IDictionary IntDic { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class Person : DemoWebApi.DemoData.Client.Entity + { - public string RequiredName { get; set; } + /// + /// Data type: Date + /// + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Date)] + [System.Runtime.Serialization.DataMember()] + public System.Nullable Baptised { get; set; } - public string Text { get; set; } + /// + /// Date of Birth. + /// This is optional. + /// + [System.Runtime.Serialization.DataMember()] + public System.Nullable DOB { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string GivenName { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Surname { get; set; } } - public class MimsPackage : object + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class PhoneNumber : object { - [System.ComponentModel.DefaultValueAttribute(20)] - [System.ComponentModel.DataAnnotations.Range(typeof(System.Int32), "10", "100", ErrorMessage="KK has to be between 10 and 100.")] - public int KK { get; set; } = 20; + [System.Runtime.Serialization.DataMember()] + public string FullNumber { get; set; } - public int KK2 { get; set; } + [System.Runtime.Serialization.DataMember()] + public DemoWebApi.DemoData.Client.PhoneType PhoneType { get; set; } + } + + /// + /// Phone type + /// Tel, Mobile, Skyp and Fax + /// + /// + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public enum PhoneType + { - public System.Nullable OptionalEnum { get; set; } + /// + /// Land line + /// + [System.Runtime.Serialization.EnumMember()] + Tel, - public System.Nullable OptionalInt { get; set; } + /// + /// Mobile phone + /// + [System.Runtime.Serialization.EnumMember()] + Mobile, - public DemoWebApi.DemoData.Client.MimsResult Result { get; set; } + [System.Runtime.Serialization.EnumMember()] + Skype, - public string Tag { get; set; } + [System.Runtime.Serialization.EnumMember()] + Fax, } +} +namespace Fonlow.AspNetCore.Identity.Client +{ - public enum MyEnumType + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class IdentitySeeding : object { - First = 1, + [System.Runtime.Serialization.DataMember()] + public string[] Roles { get; set; } - Two = 2, + [System.Runtime.Serialization.DataMember()] + public Fonlow.AspNetCore.Identity.Client.UserInitModel[] Users { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class UserInitModel : Fonlow.AspNetCore.Identity.Client.UsernameModel + { + + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string FullName { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Role { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class UsernameModel : object + { + + [System.Runtime.Serialization.DataMember()] + public string Password { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Username { get; set; } + } +} +namespace Fonlow.AspNetCore.OAuth2.Client +{ + + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class AccessTokenResponse : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="access_token")] + [System.Text.Json.Serialization.JsonPropertyName("access_token")] + public string AccessToken { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="expires_in")] + [System.Text.Json.Serialization.JsonPropertyName("expires_in")] + public int ExpiresIn { get; set; } + + [System.Runtime.Serialization.DataMember(Name="refresh_token")] + [System.Text.Json.Serialization.JsonPropertyName("refresh_token")] + public string RefreshToken { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Scope { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="token_type")] + [System.Text.Json.Serialization.JsonPropertyName("token_type")] + public string TokenType { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class RefreshAccessTokenRequest : Fonlow.AspNetCore.OAuth2.Client.RequestBase + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="refresh_token")] + [System.Text.Json.Serialization.JsonPropertyName("refresh_token")] + public string RefreshTokent { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Scope { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class RequestBase : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="grant_type")] + [System.Text.Json.Serialization.JsonPropertyName("grant_type")] + public string GrantType { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ROPCRequst : Fonlow.AspNetCore.OAuth2.Client.RequestBase + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string Password { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Scope { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string Username { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class TokenResponseBase : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember(Name="token_type")] + [System.Text.Json.Serialization.JsonPropertyName("token_type")] + public string TokenType { get; set; } + } +} +namespace Fonlow.WebApp.Accounts.Client +{ + + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class AddExternalLoginBindingModel : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string ExternalAccessToken { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ApiKey : object + { + + [System.Runtime.Serialization.DataMember()] + public System.DateTimeOffset ExpiryTime { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Key { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ChangePasswordBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string ConfirmPassword { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string NewPassword { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string OldPassword { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class CustomToken : object + { + + [System.Runtime.Serialization.DataMember()] + public System.Guid ConnectionId { get; set; } + + [System.Runtime.Serialization.DataMember()] + public System.DateTimeOffset Stamp { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string TokenValue { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ExternalLoginViewModel : object + { + + [System.Runtime.Serialization.DataMember()] + public string Name { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string State { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Url { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ManageInfoViewModel : object + { + + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + + [System.Runtime.Serialization.DataMember()] + public Fonlow.WebApp.Accounts.Client.ExternalLoginViewModel[] ExternalLoginProviders { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string LocalLoginProvider { get; set; } + + [System.Runtime.Serialization.DataMember()] + public Fonlow.WebApp.Accounts.Client.UserLoginInfoViewModel[] Logins { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class RegisterBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string ConfirmPassword { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string FullName { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string Password { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string UserName { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class RegisterExternalBindingModel : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class RemoveLoginBindingModel : object + { + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string LoginProvider { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + public string ProviderKey { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class ResetPasswordViewModel : object + { + + [System.Runtime.Serialization.DataMember()] + public string Code { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string ConfirmPassword { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Password { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class SetPasswordBindingModel : object + { + + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string ConfirmPassword { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] + [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] + [System.Runtime.Serialization.DataMember()] + public string NewPassword { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class SetUserPasswordBindingModel : Fonlow.WebApp.Accounts.Client.SetPasswordBindingModel + { + + [System.Runtime.Serialization.DataMember()] + public string UserId { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class UserInfoViewModel : object + { + + [System.Runtime.Serialization.DataMember()] + public System.DateTime CreatedUtc { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string Email { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string FullName { get; set; } + + [System.Runtime.Serialization.DataMember()] + public bool HasRegistered { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.Runtime.Serialization.DataMember(IsRequired =true)] + public System.Guid Id { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string LoginProvider { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string[] Roles { get; set; } + + [System.ComponentModel.DataAnnotations.RequiredAttribute()] + [System.Runtime.Serialization.DataMember(IsRequired =true)] + public string UserName { get; set; } + } + + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class UserLoginInfoViewModel : object + { + + [System.Runtime.Serialization.DataMember()] + public string LoginProvider { get; set; } + + [System.Runtime.Serialization.DataMember()] + public string ProviderKey { get; set; } } } namespace Core3WebApi.Controllers.Client @@ -8493,7 +8172,8 @@ namespace Core3WebApi.Controllers.Client using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; - using Newtonsoft.Json; + using System.Text.Json; + using System.Text.Json.Serialization; using Fonlow.Net.Http; @@ -8502,9 +8182,9 @@ public partial class Statistics private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public Statistics(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -8519,7 +8199,7 @@ public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings json /// /// GET api/Statistics/distribution /// - public async Task GetDistributionAsync(Action handleHeaders = null) + public async Task GetDistributionAsync(Action handleHeaders = null) { var requestUri = "api/Statistics/distribution"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8530,9 +8210,7 @@ public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings json responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8543,7 +8221,7 @@ public Statistics(System.Net.Http.HttpClient client, JsonSerializerSettings json /// /// GET api/Statistics/distribution /// - public Newtonsoft.Json.Linq.JObject GetDistribution(Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject GetDistribution(Action handleHeaders = null) { var requestUri = "api/Statistics/distribution"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8554,9 +8232,7 @@ public Newtonsoft.Json.Linq.JObject GetDistribution(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8572,7 +8248,8 @@ namespace DemoCoreWeb.Controllers.Client using System.Collections.Generic; using System.Threading.Tasks; using System.Net.Http; - using Newtonsoft.Json; + using System.Text.Json; + using System.Text.Json.Serialization; using Fonlow.Net.Http; @@ -8584,9 +8261,9 @@ public partial class SpecialTypes private System.Net.Http.HttpClient client; - private JsonSerializerSettings jsonSerializerSettings; + private JsonSerializerOptions jsonSerializerSettings; - public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings jsonSerializerSettings=null) + public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings=null) { if (client == null) throw new ArgumentNullException(nameof(client), "Null HttpClient."); @@ -8603,7 +8280,7 @@ public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings js /// GET api/SpecialTypes/AnonymousDynamic /// /// dyanmic things - public async Task GetAnonymousDynamicAsync(Action handleHeaders = null) + public async Task GetAnonymousDynamicAsync(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousDynamic"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8614,9 +8291,7 @@ public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings js responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8629,7 +8304,7 @@ public SpecialTypes(System.Net.Http.HttpClient client, JsonSerializerSettings js /// GET api/SpecialTypes/AnonymousDynamic /// /// dyanmic things - public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject GetAnonymousDynamic(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousDynamic"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8640,9 +8315,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8653,7 +8326,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action /// GET api/SpecialTypes/AnonymousDynamic2 /// - public async Task GetAnonymousDynamic2Async(Action handleHeaders = null) + public async Task GetAnonymousDynamic2Async(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousDynamic2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8664,9 +8337,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8677,7 +8348,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic(Action /// GET api/SpecialTypes/AnonymousDynamic2 /// - public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject GetAnonymousDynamic2(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousDynamic2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8688,9 +8359,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8701,7 +8370,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action /// GET api/SpecialTypes/AnonymousObject /// - public async Task GetAnonymousObjectAsync(Action handleHeaders = null) + public async Task GetAnonymousObjectAsync(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8712,9 +8381,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8725,7 +8392,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousDynamic2(Action /// GET api/SpecialTypes/AnonymousObject /// - public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject GetAnonymousObject(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8736,9 +8403,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8749,7 +8414,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action /// GET api/SpecialTypes/AnonymousObject2 /// - public async Task GetAnonymousObject2Async(Action handleHeaders = null) + public async Task GetAnonymousObject2Async(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8760,9 +8425,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8773,7 +8436,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject(Action /// GET api/SpecialTypes/AnonymousObject2 /// - public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject GetAnonymousObject2(Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); @@ -8784,9 +8447,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8797,14 +8458,11 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action /// POST api/SpecialTypes/AnonymousObject /// - public async Task PostAnonymousObjectAsync(Newtonsoft.Json.Linq.JObject obj, Action handleHeaders = null) + public async Task PostAnonymousObjectAsync(System.Text.Json.Nodes.JsonObject obj, Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, obj); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(obj, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -8813,9 +8471,7 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8826,14 +8482,11 @@ public Newtonsoft.Json.Linq.JObject GetAnonymousObject2(Action /// POST api/SpecialTypes/AnonymousObject /// - public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JObject obj, Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject PostAnonymousObject(System.Text.Json.Nodes.JsonObject obj, Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, obj); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(obj, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -8842,9 +8495,7 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8855,14 +8506,11 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb /// /// POST api/SpecialTypes/AnonymousObject2 /// - public async Task PostAnonymousObject2Async(Newtonsoft.Json.Linq.JObject obj, Action handleHeaders = null) + public async Task PostAnonymousObject2Async(System.Text.Json.Nodes.JsonObject obj, Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, obj); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(obj, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = await client.SendAsync(httpRequestMessage); @@ -8871,9 +8519,7 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = await responseMessage.Content.ReadAsStreamAsync(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8884,14 +8530,11 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject(Newtonsoft.Json.Linq.JOb /// /// POST api/SpecialTypes/AnonymousObject2 /// - public Newtonsoft.Json.Linq.JObject PostAnonymousObject2(Newtonsoft.Json.Linq.JObject obj, Action handleHeaders = null) + public System.Text.Json.Nodes.JsonObject PostAnonymousObject2(System.Text.Json.Nodes.JsonObject obj, Action handleHeaders = null) { var requestUri = "api/SpecialTypes/AnonymousObject2"; using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - using var requestWriter = new System.IO.StringWriter(); - var requestSerializer = JsonSerializer.Create(jsonSerializerSettings); - requestSerializer.Serialize(requestWriter, obj); - var content = new StringContent(requestWriter.ToString(), System.Text.Encoding.UTF8, "application/json"); + var content = System.Net.Http.Json.JsonContent.Create(obj, mediaType: null, jsonSerializerSettings); httpRequestMessage.Content = content; handleHeaders?.Invoke(httpRequestMessage.Headers); var responseMessage = client.Send(httpRequestMessage); @@ -8900,9 +8543,7 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject2(Newtonsoft.Json.Linq.JO responseMessage.EnsureSuccessStatusCodeEx(); if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } var stream = responseMessage.Content.ReadAsStream(); - using JsonReader jsonReader = new JsonTextReader(new System.IO.StreamReader(stream)); - var serializer = JsonSerializer.Create(jsonSerializerSettings); - return serializer.Deserialize(jsonReader); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); } finally { @@ -8911,106 +8552,6 @@ public Newtonsoft.Json.Linq.JObject PostAnonymousObject2(Newtonsoft.Json.Linq.JO } } } -namespace Fonlow.AspNetCore.OAuth2.Client -{ - - - public class RequestBase : object - { - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string GrantType { get; set; } - } -} -namespace Fonlow.WebApp.Accounts.Client -{ - - - public class UserInfoViewModel : object - { - - public System.DateTime CreatedUtc { get; set; } - - public string Email { get; set; } - - public string FullName { get; set; } - - public bool HasRegistered { get; set; } - - public System.Guid Id { get; set; } - - public string LoginProvider { get; set; } - - public string[] Roles { get; set; } - - public string UserName { get; set; } - } - - public class ChangePasswordBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string OldPassword { get; set; } - } - - public class RegisterBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - public string Email { get; set; } - - public string FullName { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string Password { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - public string UserName { get; set; } - } - - public class ResetPasswordViewModel : object - { - - public string Code { get; set; } - - public string ConfirmPassword { get; set; } - - public string Email { get; set; } - - public string Password { get; set; } - } - - public class SetPasswordBindingModel : object - { - - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string ConfirmPassword { get; set; } - - [System.ComponentModel.DataAnnotations.RequiredAttribute()] - [System.ComponentModel.DataAnnotations.StringLength(100, MinimumLength=6, ErrorMessage="The {0} must be at least {2} characters long.")] - [System.ComponentModel.DataAnnotations.DataType(System.ComponentModel.DataAnnotations.DataType.Password)] - public string NewPassword { get; set; } - } - - public class SetUserPasswordBindingModel : Fonlow.WebApp.Accounts.Client.SetPasswordBindingModel - { - - public string UserId { get; set; } - } -} namespace Fonlow.Net.Http { diff --git a/DemoWebApi.DemoDataCore/Entities.cs b/DemoWebApi.DemoDataCore/Entities.cs index 185d406..5b2b16d 100644 --- a/DemoWebApi.DemoDataCore/Entities.cs +++ b/DemoWebApi.DemoDataCore/Entities.cs @@ -374,16 +374,19 @@ namespace DemoWebApi.DemoData.Another /// with X and Y /// for Demo /// + [DataContract(Namespace = Constants.DataNamespace)] public struct MyPoint { /// /// X /// + [DataMember] public double X; /// /// Y /// + [DataMember] public double Y; } } diff --git a/Fonlow.AspNetCore.Identity/OAuth2Models.cs b/Fonlow.AspNetCore.Identity/OAuth2Models.cs new file mode 100644 index 0000000..71d5bde --- /dev/null +++ b/Fonlow.AspNetCore.Identity/OAuth2Models.cs @@ -0,0 +1,102 @@ +//using System; +//using System.Collections.Generic; +//using System.ComponentModel.DataAnnotations; +//using System.Linq; +//using System.Runtime.Serialization; +//using System.Text; +//using System.Text.Json.Serialization; +//using System.Threading.Tasks; + +//// https://datatracker.ietf.org/doc/html/rfc6749 +//namespace Fonlow.AspNetCore.OAuth2 +//{ + +// [JsonDerivedType(typeof(ROPCRequst), "password")] +// [JsonDerivedType(typeof(RefreshAccessTokenRequest), "refresh_token")] +// [DataContract] +// public class RequestBase +// { +// [Required] +// [JsonPropertyName("grant_type")] +// [DataMember(Name ="grant_type")] +// [JsonPropertyOrder(-10)] +// public string GrantType { get; set; } +// } + +// /// +// /// Section 4.3 and 4.3.2. +// /// GrantType must be Value MUST be set to "password". +// /// +// [DataContract] +// public class ROPCRequst : RequestBase +// { +// [Required] +// [DataMember] +// public string Username { get; set; } + +// [Required] +// [DataMember] +// public string Password { get; set; } + +// [DataMember] +// public string Scope { get; set; } + +// } + +// /// +// /// Section 6 +// /// Grant type MUST be set to "refresh_token". +// /// +// [DataContract] +// public class RefreshAccessTokenRequest : RequestBase +// { +// [Required] +// [JsonPropertyName("refresh_token")] +// [DataMember(Name = "refresh_token")] +// public string RefreshTokent { get; set; } + +// [DataMember] +// public string Scope { get; set; } +// } + +// [DataContract] +// public abstract class TokenResponseBase +// { +// [Required] +// [JsonPropertyName("token_type")] +// [DataMember(Name = "token_type")] +// public string TokenType { get; set; } +// } + +// /// +// /// Section 5.1 +// /// +// [DataContract] +// public class AccessTokenResponse +// { +// [JsonPropertyName("access_token")] +// [DataMember(Name = "access_token")] +// [Required] +// public string AccessToken { get; set; } + +// [JsonPropertyName("token_type")] +// [DataMember(Name = "token_type")] +// [Required] +// public string TokenType { get; set; } + +// /// +// /// In the spec, it is recommended, however, it is bad in practice if not required. +// /// +// [JsonPropertyName("expires_in")] +// [DataMember(Name = "expires_in")] +// [Required] +// public int ExpiresIn { get; set; } + +// [JsonPropertyName("refresh_token")] +// [DataMember(Name = "refresh_token")] +// public string RefreshToken { get; set; } + +// [DataMember] +// public string Scope { get; set; } +// } +//} diff --git a/Fonlow.Auth.PayloadConverters/Fonlow.Auth.PayloadConverters.csproj b/Fonlow.Auth.PayloadConverters/Fonlow.Auth.PayloadConverters.csproj new file mode 100644 index 0000000..81a68c4 --- /dev/null +++ b/Fonlow.Auth.PayloadConverters/Fonlow.Auth.PayloadConverters.csproj @@ -0,0 +1,8 @@ + + + + net8.0 + enable + + + diff --git a/Fonlow.Auth.PayloadConverters/Models.cs b/Fonlow.Auth.PayloadConverters/Models.cs new file mode 100644 index 0000000..c769a03 --- /dev/null +++ b/Fonlow.Auth.PayloadConverters/Models.cs @@ -0,0 +1,96 @@ +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Fonlow.Auth.Models +{ +// Data contract attbibutes are basically for NewtonSoft.Json which respects these attributes + //[JsonPolymorphic(TypeDiscriminatorPropertyName = "grant_type")] + //[JsonDerivedType(typeof(ROPCRequst), "password")] + //[JsonDerivedType(typeof(RefreshAccessTokenRequest), "refresh_token")] + [DataContract] + public class RequestBase + { + [Required] + [JsonPropertyName("grant_type")] + [JsonPropertyOrder(-10)] + [DataMember(Name = "grant_type")] + public string GrantType { get; set; } + } + + /// + /// Section 4.3 and 4.3.2. + /// GrantType must be Value MUST be set to "password". + /// + [DataContract] + public class ROPCRequst : RequestBase + { + [Required] + [DataMember] + public string Username { get; set; } + + [Required] + [DataMember] + public string Password { get; set; } + + [DataMember] + public string Scope { get; set; } + + } + + /// + /// Section 6 + /// Grant type MUST be set to "refresh_token". + /// + [DataContract] + public class RefreshAccessTokenRequest : RequestBase + { + [Required] + [JsonPropertyName("refresh_token")] + [DataMember(Name = "refresh_token")] + public string RefreshToken { get; set; } + + [DataMember] + public string Scope { get; set; } + } + + [DataContract] + public abstract class TokenResponseBase + { + /// + /// Such as bearer or Bearer + /// + [Required] + [JsonPropertyName("token_type")] + [DataMember(Name = "token_type")] + public string TokenType { get; set; } + } + + /// + /// Section 5.1 + /// + [DataContract] + public class AccessTokenResponse : TokenResponseBase + { + [JsonPropertyName("access_token")] + [DataMember(Name = "access_token")] + [Required] + public string AccessToken { get; set; } + + /// + /// In the spec, it is recommended, however, it is bad in practice if not required. + /// + [JsonPropertyName("expires_in")] + [DataMember(Name = "expires_in")] + [Required] + public int ExpiresIn { get; set; } + + [JsonPropertyName("refresh_token")] + [DataMember(Name = "refresh_token")] + public string RefreshToken { get; set; } + + [DataMember] + public string Scope { get; set; } + } + +} diff --git a/Fonlow.Auth.PayloadConverters/TokenRequestConverter.cs b/Fonlow.Auth.PayloadConverters/TokenRequestConverter.cs new file mode 100644 index 0000000..3cea76e --- /dev/null +++ b/Fonlow.Auth.PayloadConverters/TokenRequestConverter.cs @@ -0,0 +1,129 @@ +using Fonlow.Auth.Models; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Fonlow.Text.Json.Auth +{ + public sealed class TokenRequestConverter : JsonConverter + { + public override bool HandleNull => true; + + public override void Write(Utf8JsonWriter writer, RequestBase value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString("grant_type", value.GrantType); + switch (value.GrantType) + { + case "password": + ROPCRequst ropcRequest = value as ROPCRequst; + writer.WriteString("username", ropcRequest.Username); + writer.WriteString("password", ropcRequest.Password); + writer.WriteString("scope", ropcRequest.Scope); + break; + case "refresh_token": + RefreshAccessTokenRequest refreshRequest = value as RefreshAccessTokenRequest; + writer.WriteString("refresh_token", refreshRequest.RefreshToken); + writer.WriteString("scope", refreshRequest.Scope); + break; + default: + throw new NotSupportedException(); + } + + writer.WriteEndObject(); + } + + public override RequestBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.PropertyName) + { + throw new JsonException(); + } + + string propertyName = reader.GetString(); + if (propertyName != "grant_type") + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException(); + } + + var typeDiscriminator = reader.GetString(); + + switch (typeDiscriminator) + { + case "password": + var ropcRequest = new ROPCRequst(); + ropcRequest.GrantType = typeDiscriminator; + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndObject) + { + return ropcRequest; + } + + if (reader.TokenType == JsonTokenType.PropertyName) + { + propertyName = reader.GetString(); + if (reader.Read()) + { + switch (propertyName) + { + case "username": + ropcRequest.Username = reader.GetString(); + break; + case "password": + ropcRequest.Password = reader.GetString(); + break; + case "scope": + ropcRequest.Scope = reader.GetString(); + break; + } + } + } + } + + return ropcRequest; + case "refresh_token": + var refreshTokenRequest = new RefreshAccessTokenRequest(); + refreshTokenRequest.GrantType = typeDiscriminator; + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndObject) + { + return refreshTokenRequest; + } + + if (reader.TokenType == JsonTokenType.PropertyName) + { + propertyName = reader.GetString(); + if (reader.Read()) + { + switch (propertyName) + { + case "refresh_token": + refreshTokenRequest.RefreshToken = reader.GetString(); + break; + case "scope": + refreshTokenRequest.Scope = reader.GetString(); + break; + } + } + } + } + return refreshTokenRequest; + default: + throw new JsonException(); + } + } + } +} diff --git a/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs b/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs new file mode 100644 index 0000000..131fe15 --- /dev/null +++ b/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs @@ -0,0 +1,109 @@ +using Fonlow.Auth.Models; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Fonlow.Text.Json.Auth +{ + public sealed class TokenResponseConverter : JsonConverter + { + public override bool HandleNull => true; + + public override void Write(Utf8JsonWriter writer, TokenResponseBase value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString("token_type", value.TokenType); + switch (value.TokenType) + { + case "bearer": + case "Bearer": + AccessTokenResponse accessTokenResponse = value as AccessTokenResponse; + writer.WriteString("access_token", accessTokenResponse.AccessToken); + writer.WriteNumber("expires_in", Convert.ToDecimal(accessTokenResponse.ExpiresIn)); + if (!string.IsNullOrWhiteSpace(accessTokenResponse.RefreshToken)) + { + writer.WriteString("refresh_token", accessTokenResponse.RefreshToken); + } + + if (!string.IsNullOrWhiteSpace(accessTokenResponse.Scope)) + { + writer.WriteString("scope", accessTokenResponse.Scope); + } + break; + default: + throw new NotSupportedException(); + } + + writer.WriteEndObject(); + } + + public override TokenResponseBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.PropertyName) + { + throw new JsonException(); + } + + string propertyName = reader.GetString(); + if (propertyName != "token_type") + { + throw new JsonException(); + } + + reader.Read(); + if (reader.TokenType != JsonTokenType.String) + { + throw new JsonException(); + } + + var typeDiscriminator = reader.GetString(); + + switch (typeDiscriminator) + { + case "bearer": + case "Bearer": + var accessTokenResponse = new AccessTokenResponse(); + accessTokenResponse.TokenType = typeDiscriminator; + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndObject) + { + return accessTokenResponse; + } + + if (reader.TokenType == JsonTokenType.PropertyName) + { + propertyName = reader.GetString(); + if (reader.Read()) + { + switch (propertyName) + { + case "access_token": + accessTokenResponse.AccessToken = reader.GetString(); + break; + case "refresh_token": + accessTokenResponse.AccessToken = reader.GetString(); + break; + case "expires_in": + accessTokenResponse.ExpiresIn = reader.GetInt32(); + break; + case "scope": + accessTokenResponse.Scope = reader.GetString(); + break; + } + } + } + } + + return accessTokenResponse; + default: + throw new JsonException(); + } + } + } +} diff --git a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj index de1a572..7798741 100644 --- a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj +++ b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj @@ -29,6 +29,7 @@ + diff --git a/Fonlow.WebApp.Accounts/UsernameModel.cs b/Fonlow.WebApp.Accounts/UsernameModel.cs index 0439d62..e244548 100644 --- a/Fonlow.WebApp.Accounts/UsernameModel.cs +++ b/Fonlow.WebApp.Accounts/UsernameModel.cs @@ -1,4 +1,4 @@ -using Fonlow.AspNetCore.OAuth2; + using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text.Json.Serialization; @@ -9,7 +9,7 @@ namespace Fonlow.WebApp.Accounts /// https://datatracker.ietf.org/doc/html/rfc7519 JWT /// https://www.ietf.org/rfc/rfc6749.txt, The OAuth 2.0 Authorization Framework /// - public class TokenResponseModel : AccessTokenResponse + public class TokenResponseModel : Fonlow.Auth.Models.AccessTokenResponse { [JsonPropertyName("username")] [Required] diff --git a/PublishMySqlPluginToWebApiDebug.ps1 b/PublishMySqlPluginToWebApiDebug.ps1 new file mode 100644 index 0000000..dff034b --- /dev/null +++ b/PublishMySqlPluginToWebApiDebug.ps1 @@ -0,0 +1,8 @@ +# Because of decoupling from DB engines, the Web API needs the assemblies of a specific DB engine plugin. +# This script is to publish MySql plugin to the Web API release build during development. +# During deployment, system admin may switch to a DB engine with a bare deployment of the Web API, and copy the plugin assmeblies, and then adjust the appsetting.json file. +Set-Location $PSScriptRoot +$netVersion = "net8.0" +$RuntimeId = ([System.Runtime.InteropServices.RuntimeInformation]::RuntimeIdentifier.ToString()) +Write-Output $RuntimeId +dotnet publish ./Fonlow.EntityFrameworkCore.MySql/Fonlow.EntityFrameworkCore.MySql.csproj -r $RuntimeId --configuration Debug --output ./Core3WebApi/bin/Debug/$netVersion \ No newline at end of file diff --git a/Tests/IntegrationTestShared/DateTypesIntegration.cs b/Tests/IntegrationTestShared/DateTypesIntegration.cs deleted file mode 100644 index 4af66bc..0000000 --- a/Tests/IntegrationTestShared/DateTypesIntegration.cs +++ /dev/null @@ -1,280 +0,0 @@ -using System; -using Xunit; - -namespace IntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class DateTypesApiIntegration : IClassFixture - { - public DateTypesApiIntegration(DateTypesFixture fixture) - { - api = fixture.Api; - } - - readonly DemoWebApi.Controllers.Client.DateTypes api; - - [Fact] - public void TestGetDateTime() - { - var dt = api.GetDateTime(true); - Assert.True((DateTime.Now - dt.Value) < TimeSpan.FromSeconds(2)); - } - - [Fact] - public void TestGetNextYear() - { - var dtNow = DateTime.Now; - Assert.Equal(dtNow.AddYears(1).ToUniversalTime(), api.GetNextYear(dtNow)); - } - - [Fact] - public void TestGetUtcNowNextYear() - { - var dtNow = DateTime.UtcNow; - Assert.Equal(dtNow.AddYears(1), api.GetNextYear(dtNow).ToUniversalTime()); - } - - [Fact] - public void TestGetNextHour() - { - var dtNow = DateTimeOffset.Now; - Assert.Equal(dtNow.AddHours(1), api.GetNextHour(dtNow)); - } - - [Fact] - public void TestGetNextYearNullable() - { - var dtNow = DateTime.Now; - Assert.Equal(dtNow.AddYears(2).ToUniversalTime(), api.GetNextYearNullable(2, dtNow)); - } - - - [Fact] - public void TestGetNextHourNullable() - { - var dtNow = DateTimeOffset.Now; - Assert.Equal(dtNow.AddHours(2), api.GetNextHourNullable(2, dtNow)); - } - - [Fact] - public void TestGetNextYearNullable2() - { - var dtNow = DateTime.Now; - Assert.Equal(dtNow.AddYears(2).Year, api.GetNextYearNullable(2, null).Year); - } - - - [Fact] - public void TestGetNextHourNullable2() - { - var dtNow = DateTimeOffset.Now; - Assert.Equal(dtNow.AddHours(2).Hour, api.GetNextHourNullable(2, null).Hour); - } - - [Fact] - public void TestIsDateTimeDate() - { - var d = new DateTime(2022, 2, 13); //Kind unspecified. So it works for Date - Assert.Equal(DateTimeKind.Unspecified, d.Kind); - Assert.Equal(TimeSpan.Zero, d.TimeOfDay); - var dr = api.IsDateTimeDate(d); - Assert.Equal(d, dr.Item2); - Assert.Equal(d.Day, dr.Item1.Day); - } - - [Fact] - public void TestIsDateTimeOffsetDate() - { - var d = new DateTime(2022, 2, 13); - Assert.Equal(DateTimeKind.Unspecified, d.Kind); - Assert.Equal(TimeSpan.Zero, d.TimeOfDay); - DateTimeOffset ds = new DateTimeOffset(d, TimeSpan.Zero); - var dr = api.IsDateTimeOffsetDate(ds); - Assert.Equal(d.Day, dr.Item1.Day); - Assert.Equal(ds.Day, dr.Item1.Day); - //Assert.Equal(ds, dr.Item2); if client and server are at different timezone, this will fail. - } - - [Fact] - public void TestIsDateTimeOffsetDate2() - { - DateTimeOffset ds = new DateTimeOffset(2022, 2, 13, 0, 0, 0, TimeSpan.Zero); - var dr = api.IsDateTimeOffsetDate(ds); - Assert.Equal(ds.Day, dr.Item1.Day); - //Assert.Equal(ds, dr.Item2); if client and server are at different timezone, this will fail. - } - - [Fact] - public void TestSearcDateRange() - { - var dtStart = DateTime.Today; - var dtEnd = dtStart.AddDays(5); - var t = api.SearchDateRange(dtStart, dtEnd); - Assert.Equal(dtStart.ToUniversalTime(), t.Item1); - Assert.Equal(dtEnd.ToUniversalTime(), t.Item2); - } - - [Fact] - public void TestSearcDateRangeWithEndDateNull() - { - var dtStart = DateTime.Today; - //var dtEnd = dtStart.AddDays(5); - var t = api.SearchDateRange(dtStart, null); - Assert.Equal(dtStart.ToUniversalTime(), t.Item1); - Assert.False(t.Item2.HasValue); - } - - [Fact] - public void TestSearcDateRangeWithBothNull() - { - //var dtStart = DateTime.Today; - //var dtEnd = dtStart.AddDays(5); - var t = api.SearchDateRange(null, null); - Assert.False(t.Item1.HasValue); - Assert.False(t.Item2.HasValue); - } - - [Fact] - public void TestGetUtcNowNextHour() - { - var dtNow = DateTimeOffset.UtcNow; - Assert.Equal(dtNow.AddHours(1), api.GetNextHour(dtNow)); - } - - [Fact] - public void TestPostNextYear() - { - var dtNow = DateTime.Now; - Assert.Equal(dtNow.AddYears(1), api.PostNextYear(dtNow)); - } - - [Fact] - public void TestGetDateTimeNull() - { - var dt = api.GetDateTime(false); - Assert.False(dt.HasValue); - } - - [Fact] - public void TestGetDateTimeOffset() - { - var dt = api.GetDateTimeOffset(); - Assert.True((DateTime.Now - dt) < TimeSpan.FromSeconds(2)); - } - - [Fact] - public void TestPostDateTimeOffset() - { - var p = DateTimeOffset.Now; - var r = api.PostDateTimeOffset(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeOffsetDate() - { - var p = DateTimeOffset.Now.Date; - var r = api.PostDateTimeOffset(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeOffsetMin() - { - var p = DateTimeOffset.MinValue; - var r = api.PostDateTimeOffset(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeOffsetNullable() - { - var p = DateTimeOffset.Now; - var r = api.PostDateTimeOffsetNullable(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeOffsetNullableWithNull() - { - var r = api.PostDateTimeOffsetNullable(null); - Assert.Null(r); - } - - [Fact] - public void TestRouteDateTimeOffset() - { - var p = DateTimeOffset.Now; - var r = api.RouteDateTimeOffset(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTime() - { - var p = DateTime.Now; - var r = api.PostDateTime(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeDate() - { - var p = DateTime.Now.Date; - var r = api.PostDateTime(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateTimeMin() - { - var p = DateTime.MinValue; - var r = api.PostDateTime(p); - Assert.Equal(p, r); - } - - [Fact] - public void TestPostDateOnly() - { - var dateOnly = new DateOnly(1988, 12, 23); - var r = api.PostDateOnly(dateOnly); - Assert.Equal(dateOnly, r); - } - - [Fact] - public void TestPostDateOnlyNullable() - { - var dateOnly = new DateOnly(1988, 12, 23); - var r = api.PostDateOnlyNullable(dateOnly); - Assert.Equal(dateOnly, r); - } - - [Fact] - public void TestPostDateOnlyNullableWithNull() - { - var r = api.PostDateOnlyNullable(null); - Assert.Null(r); - } - - [Fact] - public async void TestQueryDateOnlyString() - { - DateOnly d = new DateOnly(2008, 12, 18); - var r = await api.QueryDateOnlyAsStringAsync(d.ToString("O")); - Assert.Equal(d, r); - } - - [Fact] - public void TestSearcDateRangeWithStartDateNull()//asp.net web api won't accept such call. - { - var dtStart = DateTime.Today; - var dtEnd = dtStart.AddDays(5); - var r = api.SearchDateRange(null, dtEnd); - Assert.Null(r.Item1); - Assert.Equal(dtEnd.ToUniversalTime(), r.Item2); - } - - - - } -} diff --git a/Tests/IntegrationTestShared/DotNetCoreSpecial.cs b/Tests/IntegrationTestShared/DotNetCoreSpecial.cs deleted file mode 100644 index 46093a3..0000000 --- a/Tests/IntegrationTestShared/DotNetCoreSpecial.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using Xunit; - -namespace IntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class DotNetCoreSpecial : IClassFixture - { - public DotNetCoreSpecial(SuperDemoFixture fixture) - { - api = fixture.Api; - } - - readonly DemoWebApi.Controllers.Client.SuperDemo api; - - [Fact] - public void TestGetDictionary() - { - var dic = api.GetDictionary(); - Assert.Equal("number", dic["System.Int64"]); - } - - [Fact] - public void TestGetDictionaryOfPeople() - { - var dic = api.GetDictionaryOfPeople(); - Assert.Equal("Tony Stark", dic["Iron Man"].Name); - Assert.Equal("New York", dic["Spider Man"].Addresses[0].City); - Assert.Throws< System.Collections.Generic.KeyNotFoundException >(() => dic["iron Man"].Name); //the camelCase filter is in play in the web api - } - - [Fact] - public void TestGetEmptyString() - { - Assert.Equal("\"\"", api.GetEmptyString()); - } - - [Fact] - public void TestGetNullString() - { - Assert.Null(api.GetNullString()); - } - - [Fact] - public void TestZeroWithFloatDoubleAndDecimal() - { - // Assert.NotEqual(0f, 0.1f + 0.2f - 0.3f);//In VS 2015 update 2, compiler makes it zeror. - Assert.NotEqual(0d, 0.1d + 0.2d - 0.3d); - Assert.Equal(0m, 0.1m + 0.2m - 0.3m); - - Assert.Equal(0, api.GetFloatZero()); - Assert.NotEqual(0, api.GetDoubleZero());//.net core is consistent in both client side and server side. - Assert.Equal(0, api.GetDecimalZero()); - - } - } -} diff --git a/Tests/IntegrationTestShared/EntitiesApiIntegration.cs b/Tests/IntegrationTestShared/EntitiesApiIntegration.cs index 66deb53..e7e9502 100644 --- a/Tests/IntegrationTestShared/EntitiesApiIntegration.cs +++ b/Tests/IntegrationTestShared/EntitiesApiIntegration.cs @@ -14,7 +14,6 @@ public EntitiesApiIntegration(EntitiesFixture fixture) readonly DemoWebApi.Controllers.Client.Entities api; - [Fact] public void TestCreatePerson3() { @@ -249,19 +248,6 @@ public void TestGet() Assert.Equal(1988, person.DOB.Value.Year); } - [Fact] - public void TestGetCompany() - { - var c = api.GetCompany(1); - Assert.Equal("Super Co", c.Name); - Assert.Equal(2, c.Addresses.Length); - Assert.Equal(AddressType.Postal, c.Addresses[0].Type); - Assert.Equal(AddressType.Residential, c.Addresses[1].Type); - Assert.Equal(8, c.Int2D[1, 3]); - Assert.Equal(8, c.Int2DJagged[1][3]); - - } - [Fact] public void TestGetMimsString() { diff --git a/Tests/IntegrationTestShared/IntegrationTestShared.projitems b/Tests/IntegrationTestShared/IntegrationTestShared.projitems index d645d96..f84d93c 100644 --- a/Tests/IntegrationTestShared/IntegrationTestShared.projitems +++ b/Tests/IntegrationTestShared/IntegrationTestShared.projitems @@ -9,14 +9,9 @@ IntegrationTestShared - - - - - \ No newline at end of file diff --git a/Tests/IntegrationTestShared/SpecialTypesApiIntegration.cs b/Tests/IntegrationTestShared/SpecialTypesApiIntegration.cs deleted file mode 100644 index abefc7b..0000000 --- a/Tests/IntegrationTestShared/SpecialTypesApiIntegration.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using Xunit; -using Fonlow.Testing; - -namespace IntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class SpecialTypesApiIntegration : IClassFixture - { - public SpecialTypesApiIntegration(SpecialTypesFixture fixture) - { - api = fixture.Api; - } - - readonly DemoCoreWeb.Controllers.Client.SpecialTypes api; - - [Fact] - public void TestGetAnonymousDynamic() - { - var d = api.GetAnonymousDynamic(); - Assert.Equal("12345", d["id"].ToString()); - Assert.Equal("Something", d["name"].ToString()); - } - - [Fact] - public void TestGetAnonymousObject() - { - var d = api.GetAnonymousObject(); - Assert.Equal("12345", d["id"].ToString()); - Assert.Equal("Something", d["name"].ToString()); - } - - [Fact] - public void TestPostAnonymousObject() - { - var d = new Newtonsoft.Json.Linq.JObject - { - ["Id"] = "12345", - ["Name"] = "Something" - }; - var r = api.PostAnonymousObject(d); - Assert.Equal("123451", r["Id"].ToString()); - Assert.Equal("Something1", r["Name"].ToString()); - - } - - [Fact] - public void TestGetAnonymousDynamic2() - { - var d = api.GetAnonymousDynamic2(); - Assert.Equal("12345", d["id"].ToString()); - Assert.Equal("Something", d["name"].ToString()); - } - - [Fact] - public void TestGetAnonymousObject2() - { - var d = api.GetAnonymousObject2(); - Assert.Equal("12345", d["id"].ToString()); - Assert.Equal("Something", d["name"].ToString()); - } - - [Fact] - public void TestPostAnonymousObject2() - { - var d = new Newtonsoft.Json.Linq.JObject - { - ["Id"] = "12345", - ["Name"] = "Something" - }; - var r = api.PostAnonymousObject2(d); - Assert.Equal("123451", r["Id"].ToString()); - Assert.Equal("Something1", r["Name"].ToString()); - - } - - } -} diff --git a/Tests/IntegrationTestShared/SuperDemoIntegration.cs b/Tests/IntegrationTestShared/SuperDemoIntegration.cs deleted file mode 100644 index e77506b..0000000 --- a/Tests/IntegrationTestShared/SuperDemoIntegration.cs +++ /dev/null @@ -1,556 +0,0 @@ -using DemoWebApi.DemoData.Client; -using System; -using System.Collections.Generic; -using Xunit; - -namespace IntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class SuperDemoApiIntegration : IClassFixture - { - public SuperDemoApiIntegration(SuperDemoFixture fixture) - { - api = fixture.Api; - } - - readonly DemoWebApi.Controllers.Client.SuperDemo api; - - [Fact] - public void TestGetIntArrayQ() - { - var d = api.GetIntArrayQ(new int[] { 3, 4, 5 }); - Assert.Equal(3, d.Length); - Assert.Equal(5, d[2]); - } - - [Fact] - public void TestGetIntArrayQ2() - { - var d = api.GetIntArrayQ2(new long[] { 3, 4, 5 }); - Assert.Equal(3, d.Length); - Assert.Equal(5, d[2]); - } - - [Fact] - public void TestGetDecimalArrayQ() - { - var d = api.GetDecimalArrayQ(new decimal[] { 3.5m, 4.6m, 5.7m }); - Assert.Equal(3, d.Length); - Assert.Equal(5.7m, d[2]); - } - - [Fact] - public void TestGetStringArrayQ() - { - var d = api.GetStringArrayQ(new string[] { "Abc", "Eft", "hi" }); - Assert.Equal(3, d.Length); - Assert.Equal("hi", d[2]); - } - - [Fact] - public void TestGetStringArrayQ2() - { - var d = api.GetStringArrayQ2(new string[] { "Abc", "Eft", "hi" }); - Assert.Equal(3, d.Length); - Assert.Equal("hi", d[2]); - } - - [Fact] - public void TestGetEnumArrayQ2() - { - var d = api.GetEnumArrayQ2(new DayOfWeek[] { DayOfWeek.Monday, DayOfWeek.Sunday, DayOfWeek.Saturday }); - Assert.Equal(3, d.Length); - Assert.Equal(DayOfWeek.Saturday, d[2]); - } - - [Fact] - public void TestGetEnumArrayDays() - { - var d = api.GetEnumArrayDays(new Days[] { Days.Mon, Days.Tue, Days.Wed }); - Assert.Equal(3, d.Length); - Assert.Equal(Days.Wed, d[2]); - } - - [Fact] - public void TestGetDay() - { - var d = api.GetDay(Days.Fri); - Assert.Equal(Days.Fri, d); - } - - [Fact] - public void TestPostDay() - { - var d = api.PostDay(Days.Fri, Days.Sat); - Assert.Equal(2, d.Length); - Assert.Equal(Days.Sat, d[1]); - } - - [Fact] - public void TestAthletheSearch() - { - var s = api.AthletheSearch(32, 0, null, null, null); - Assert.Equal("\"320\"", s); - } - - [Fact] - public void TestAthletheSearch2() - { - var s = api.AthletheSearch(32, 0, null, null, "Search"); - Assert.Equal("\"320Search\"", s); - } - - [Fact] - public void TestAthletheSearch3() - { - var s = api.AthletheSearch(32, 0, null, "Sort", "Search"); - Assert.Equal("\"320SortSearch\"", s); - } - - [Fact] - public void TestAthletheSearch4() - { - var s = api.AthletheSearch(32, 0, "Order", "Sort", "Search"); - Assert.Equal("\"320OrderSortSearch\"", s); - } - - [Fact] - public void TestAthletheSearch5() - { - var s = api.AthletheSearch(32, 0, "Order", null, "Search"); - Assert.Equal("\"320OrderSearch\"", s); - } - - [Fact] - public void TestAthletheSearch6() - { - var s = api.AthletheSearch(32, 0, "Order", "", "Search"); - Assert.Equal("\"320OrderSearch\"", s); - } - - [Fact] - public void TestGetIntSquare() - { - Assert.Equal(10000, api.GetIntSquare(100)); - } - - [Fact] - public void TestGetDecimalSquare() - { - Assert.Equal(10158.6241m, api.GetDecimalSquare(100.79m)); - } - - [Fact] - public void TestNullablePrimitive() - { - double dou = 1234.567; - decimal de = 1234.567m; - var t = api.GetPrimitiveNullable("abc", dou, de); - Assert.Equal(dou, t.Item2); - Assert.Equal(de, t.Item3); - } - - [Fact] - public void TestNullablePrimitiveWithFirstNull() - { - decimal de = 1234.567m; - var t = api.GetPrimitiveNullable("abc", null, de); - Assert.Null(t.Item2); - Assert.Equal(de, t.Item3); - } - - [Fact] - public void TestNullablePrimitiveWithBothNulll() - { - var t = api.GetPrimitiveNullable("abc", null, null); - Assert.Null(t.Item2); - Assert.Null(t.Item3); - } - - [Fact] - public void TestNullablePrimitiveWithSecondNull() - { - double dou = 1234.567; - var t = api.GetPrimitiveNullable("abc", dou, null); - Assert.Equal(dou, t.Item2); - Assert.Null(t.Item3); - } - - [Fact] - public void TestGetNullableDecimal() - { - var d = api.GetNullableDecimal(true); - Assert.True(d.Value > 10); - } - - [Fact] - public void TestGetDecimalNull() - { - var d = api.GetNullableDecimal(false); - Assert.False(d.HasValue); - } - - [Fact] - public void TestGetNullPerson() - { - Assert.Null(api.GetNullPerson()); - } - - [Fact] - public void TestGetByteArray() - { - var array = api.GetByteArray(); - var s = System.Text.Encoding.UTF8.GetString(array); - Assert.Equal("abcdefg", s); - } - - [Fact] - public void TestGetBool() - { - Assert.True(api.GetBool()); - } - - [Fact] - public void TestGetByte() - { - Assert.Equal(255, api.Getbyte()); - } - - [Fact] - public void TestGet() - { - Assert.Equal(-127, api.Getsbyte()); - } - - [Fact] - public void TestGetChar() - { - //var response = api.GetChar(); - //var text = response.Content.ReadAsStringAsync().Result;//Web API return only string, and does not support char directly. - //Assert.Equal("\"A\"", text); - Assert.Equal('A', api.GetChar()); - } - - [Fact] - public void TestGetDecimal() - { - Assert.Equal(decimal.MaxValue, api.GetDecimal()); - } - - [Fact] - public void TestGetDouble() - { - Assert.Equal(-1.7976931348623e308, api.Getdouble()); - } - - [Fact] - public void TestGetUint() - { - Assert.Equal(4294967295, api.GetUint()); - } - - [Fact] - public void TestGetUlong() - { - Assert.Equal(18446744073709551615, api.Getulong()); - } - - [Fact] - public void TestIntArray() - { - var d = api.GetIntArray(); - Assert.Equal(8, d[7]); - } - - [Fact] - public void TestPostIntArray() - { - Assert.True(api.PostIntArray(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 })); - } - - [Fact] - public void TestInt2D() - { - var d = api.GetInt2D(); - Assert.Equal(1, d.GetUpperBound(0)); - Assert.Equal(3, d.GetUpperBound(1)); - Assert.Equal(1, d[0, 0]); - Assert.Equal(4, d[0, 3]); - Assert.Equal(8, d[1, 3]); - } - - [Fact] - public void TestInt2DJagged() - { - var d = api.GetInt2DJagged(); - Assert.Equal(1, d.GetUpperBound(0)); - Assert.Equal(1, d[0][0]); - Assert.Equal(4, d[0][3]); - Assert.Equal(8, d[1][3]); - } - - [Fact] - public void TestPostInt2D() - { - var d = api.PostInt2D(new int[,] - { - {1,2,3, 4 }, - {5,6,7, 8 } - }); - Assert.True(d); - } - - [Fact] - public void TestPostInt2DExpectedFalse() - { - var d = api.PostInt2D(new int[,] - { - {1,2,3, 4 }, - {5,6,7, 9 } - }); - Assert.False(d); - } - - [Fact] - public void TestPostInt2DJagged() - { - var d = api.PostInt2DJagged(new int[][] - { - new int[] {1,2,3, 4 }, - new int[] {5,6,7, 8 } - }); - Assert.True(d); - } - - [Fact] - public void TestPostInt2DJaggedExpectedFalse() - { - var d = api.PostInt2DJagged(new int[][] - { - new int[] {1,2,3, 4 }, - new int[] {5,6,7, 9 } - }); - Assert.False(d); - } - - [Fact] - public void TestGetTextStream() - { - var response = api.GetTextStream(); - var stream = response.Content.ReadAsStreamAsync().Result; - using (var reader = new System.IO.StreamReader(stream)) - { - var s = reader.ReadToEnd(); - Assert.Equal("abcdefg", s); - } - - } - - [Fact] - public void TestDictionary() - { - var dic = new Dictionary() - { - {"Iron Man", new Person() - { - Name= "Tony Stark", - Surname="Stark", - GivenName="Tony" - } }, - - {"Spider Man", new Person() { - Name="Peter Parker", - Addresses= - new Address[] { new Address() { - City="New York" - - } }, - } }, - }; - - Assert.Throws(() => dic["iron Man"].Name); - Assert.Equal("New York", dic["Spider Man"].Addresses[0].City); - } - - [Fact] - public void TestPostDic() - { - var r = api.PostDictionary(new Dictionary() - { - {"Iron Man", new Person() - { - Name= "Tony Stark", - Surname="Stark", - GivenName="Tony" - } }, - - {"Spider Man", new Person() { - Name="Peter Parker", - Addresses= new Address[] { new Address() { - City="New York" - } - }, - } }, - }); - - Assert.Equal(2, r); - } - - [Fact] - public void TestGetKeyValuePair() - { - var r = api.GetKeyhValuePair(); - Assert.Equal("Spider Man", r.Key); - Assert.Equal("Peter Parker", r.Value.Name); - } - - [Fact] - public void TestGetICollection() - { - var r = api.GetICollection(); - Assert.Equal("Peter Parker", r[1].Name); - } - - [Fact] - public void TestGetCollection() - { - var r = api.GetCollection(); - Assert.Equal("Peter Parker", r[1].Name); - } - - [Fact] - public void TestGetIList() - { - var r = api.GetIList(); - Assert.Equal("Peter Parker", r[1].Name); - } - - [Fact] - public void TestGetList() - { - var r = api.GetList(); - Assert.Equal("Peter Parker", r[1].Name); - } - - [Fact] - public void TestGetIReadOnlyCollection() - { - var r = api.GetIReadOnlyCollection(); - Assert.Equal("Peter Parker", r[1].Name); - } - - [Fact] - public void TestGetIReadOnlyList() - { - var r = api.GetIReadOnlyList(); - Assert.Equal("Peter Parker", r[1].Name); - } - - - static Person[] GetPersonList() - { - return new Person[] { - new Person() - { - Name= "Tony Stark", - Surname="Stark", - GivenName="Tony" - }, - - new Person() { - Name="Peter Parker", - Addresses= new Address[] { new Address() { - City="New York" - - } }, - } - - }; - } - - - [Fact] - public void TestPostICollection() - { - Assert.Equal(2, api.PostICollection(GetPersonList())); - } - - [Fact] - public void TestPostIList() - { - Assert.Equal(2, api.PostIList(GetPersonList())); - } - - [Fact] - public void TestPostCollection() - { - Assert.Equal(2, api.PostCollection(GetPersonList())); - } - - [Fact] - public void TestPostList() - { - Assert.Equal(2, api.PostList(GetPersonList())); - } - - [Fact] - public void TestPostIReadOnlyCollection() - { - Assert.Equal(2, api.PostIReadOnlyCollection(GetPersonList())); - } - - [Fact] - public void TestPostIReadOnlyList() - { - Assert.Equal(2, api.PostIReadOnlyList(GetPersonList())); - } - - [Fact] - public void TestPostWithQueryButEmptyBody() - { - var r = api.PostWithQueryButEmptyBody("abc", 123); - Assert.Equal("abc", r.Item1); - Assert.Equal(123, r.Item2); - } - - [Fact] - public async void TestPostActionResult() - { - var m = await api.PostActionResultAsync(); - Assert.Equal(System.Net.HttpStatusCode.OK, m.StatusCode); - var s = await m.Content.ReadAsStringAsync(); - Assert.Equal("\"abcdefg\"", s); - } - - [Fact] - public async void TestGetActionResult() - { - var m = await api.GetActionResultAsync(); - Assert.Equal(System.Net.HttpStatusCode.OK, m.StatusCode); - var s = await m.Content.ReadAsStringAsync(); - Assert.Equal("\"abcdefg\"", s); - - } - - [Fact] - public async void TestGetActionResult2() - { - var m = await api.GetActionResult2Async(); - Assert.Equal(System.Net.HttpStatusCode.OK, m.StatusCode); - var s = await m.Content.ReadAsStringAsync(); - Assert.Equal("\"abcdefg\"", s); - - } - - [Fact] - public void TestPostGuids() - { - var id1 = Guid.NewGuid(); - var id2 = Guid.NewGuid(); - var ids = new Guid[] { id1, id2 }; - var r = api.PostGuids(ids); - Assert.Equal(2, r.Length); - Assert.Equal(id1, r[0]); - } - } -} diff --git a/Tests/IntegrationTestShared/TupleApiIntegration.cs b/Tests/IntegrationTestShared/TupleApiIntegration.cs deleted file mode 100644 index b4d4696..0000000 --- a/Tests/IntegrationTestShared/TupleApiIntegration.cs +++ /dev/null @@ -1,201 +0,0 @@ -using DemoWebApi.DemoData.Client; -using Newtonsoft.Json; -using System; -using Xunit; - -namespace IntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class TupleApiIntegration : IClassFixture - { - public TupleApiIntegration(TupleFixture fixture) - { - api = fixture.Api; - } - - readonly DemoWebApi.Controllers.Client.Tuple api; - - [Fact] - public void TestTuple1() - { - var r = api.GetTuple1(); - Assert.Equal(1, r.Item1); - } - - [Fact] - public void TestPostTuple1() - { - var r = api.PostTuple1(new Tuple(8)); - Assert.Equal(8, r); - } - [Fact] - public void TestTuple2() - { - var r = api.GetTuple2(); - Assert.Equal("Two", r.Item1); - Assert.Equal(2, r.Item2); - } - - [Fact] - public void TestPostTuple2() - { - var r = api.PostTuple2(new Tuple("some", 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple3() - { - var r = api.GetTuple3(); - Assert.Equal("Three", r.Item1); - } - - [Fact] - public void TestPostTuple3() - { - var r = api.PostTuple3(new Tuple("some", "", 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple4() - { - var r = api.GetTuple4(); - Assert.Equal("Four", r.Item1); - } - - [Fact] - public void TestPostTuple4() - { - var r = api.PostTuple4(new Tuple("some", "", "", 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple5() - { - var r = api.GetTuple5(); - Assert.Equal("Five", r.Item1); - } - - [Fact] - public void TestPostTuple5() - { - var r = api.PostTuple5(new Tuple("some", "", "", "", 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple6() - { - var r = api.GetTuple6(); - Assert.Equal("Six", r.Item1); - } - - [Fact] - public void TestPostTuple6() - { - var r = api.PostTuple6(new Tuple("some", "", "", "", "", 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple7() - { - var r = api.GetTuple7(); - Assert.Equal("Seven", r.Item1); - } - - [Fact] - public void TestPostTuple7() - { - var r = api.PostTuple7(new Tuple("some", "", "", "", "", 333, 3)); - Assert.Equal("some", r); - } - - [Fact] - public void TestTuple8() - { - var r = api.GetTuple8(); - Assert.Equal("Nested", r.Item1); - Assert.Equal("nine", r.Rest.Item1); - } - - [Fact] - public void TestPostTuple8() - { - var r = api.PostTuple8(new Tuple>( - "abc", "", "", "", "", "", "", new Tuple("ok", "yes", "no"))); - Assert.Equal("ok", r); - } - - - //[Fact] - //public void TestTupleCreate() - //{ - // var t = Tuple.Create("One", "Two", 2); - // var s = JsonConvert.SerializeObject(t); - - //} - - [Fact] - public void TestJsonSerializer() - { - var t = Tuple.Create("One", "Two", 2); - using (var writer = new System.IO.StringWriter()) - { - var serializer = JsonSerializer.Create(); - serializer.Serialize(writer, t); - var s = writer.ToString(); - } - } - - [Fact] - public void TestLinkPersonCompany1() - { - Person p = new Person - { - Name = "Hey OK", - }; - - Company c = new Company - { - Name = "My Co", - FoundDate = DateTime.Now, - RegisterDate=new DateOnly(2020, 12, 23), - }; - - var r = api.LinkPersonCompany1(Tuple.Create(p, c)); - Assert.Equal("Hey OK", r.Name); - } - - [Fact] - public void TestLinkPersonCompany7() - { - Person p = new Person - { - Name = "Hey OK", - }; - - Company c = new Company - { - Name = "My Co" - }; - - var r = api.LinkPeopleCompany7(Tuple.Create(p, p, p, p, p, p, c)); - Assert.Equal("Hey OK", r.Name); - } - - [Fact] - public void TestChangeName() - { - Person p = new Person - { - Name = "Hey OK", - }; - - var r = api.ChangeName(Tuple.Create("Me", p)); - Assert.Equal("Me", r.Name); - } - } -} diff --git a/Tests/IntegrationTestsCore/DateTypesFixture.cs b/Tests/IntegrationTestsCore/DateTypesFixture.cs deleted file mode 100644 index 82d1cb9..0000000 --- a/Tests/IntegrationTestsCore/DateTypesFixture.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Fonlow.DateOnlyExtensions; -using Fonlow.Testing; -using System; - -namespace IntegrationTests -{ - public class DateTypesFixture : AuthEfHttpClientWithUsername - { - public DateTypesFixture() - { - var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() - { - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - }; - - jsonSerializerSettings.Converters.Add(new DateOnlyJsonConverter()); - jsonSerializerSettings.Converters.Add(new DateOnlyNullableJsonConverter()); - - Api = new DemoWebApi.Controllers.Client.DateTypes(AuthorizedClient, jsonSerializerSettings); - } - - public DemoWebApi.Controllers.Client.DateTypes Api { get; private set; } - } -} diff --git a/Tests/IntegrationTestsCore/EntitiesFixture.cs b/Tests/IntegrationTestsCore/EntitiesFixture.cs index aa67779..8b5d78f 100644 --- a/Tests/IntegrationTestsCore/EntitiesFixture.cs +++ b/Tests/IntegrationTestsCore/EntitiesFixture.cs @@ -19,13 +19,13 @@ public class EntitiesFixture : AuthEfHttpClientWithUsername { public EntitiesFixture() { - var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() + System.Text.Json.JsonSerializerOptions jsonSerializerSettings = new System.Text.Json.JsonSerializerOptions() { - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + PropertyNameCaseInsensitive = true, + NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString, // newtonsoft.json along with converters may return long and int128 as string }; - jsonSerializerSettings.Converters.Add(new DateOnlyJsonConverter()); - jsonSerializerSettings.Converters.Add(new DateOnlyNullableJsonConverter()); Api = new DemoWebApi.Controllers.Client.Entities(AuthorizedClient, jsonSerializerSettings); } diff --git a/Tests/IntegrationTestsCore/HeroesFixture.cs b/Tests/IntegrationTestsCore/HeroesFixture.cs index b87facb..807c38d 100644 --- a/Tests/IntegrationTestsCore/HeroesFixture.cs +++ b/Tests/IntegrationTestsCore/HeroesFixture.cs @@ -7,7 +7,14 @@ public class HeroesFixture : AuthEfHttpClientWithUsername { public HeroesFixture() { - Api = new DemoWebApi.Controllers.Client.Heroes(AuthorizedClient); + System.Text.Json.JsonSerializerOptions jsonSerializerSettings = new System.Text.Json.JsonSerializerOptions() + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + PropertyNameCaseInsensitive = true, + NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString, // newtonsoft.json along with converters may return long and int128 as string + }; + + Api = new DemoWebApi.Controllers.Client.Heroes(AuthorizedClient, jsonSerializerSettings); } public DemoWebApi.Controllers.Client.Heroes Api { get; private set; } diff --git a/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs b/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs new file mode 100644 index 0000000..b4971fe --- /dev/null +++ b/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs @@ -0,0 +1,133 @@ +using Xunit; +using IntegrationTests; +using Fonlow.Auth.Models; +using DemoCoreWeb.ClientApiTextJson; +using System.Threading.Tasks; + +namespace TextJsonIntegrationTests +{ + [Collection(TestConstants.LaunchWebApiAndInit)] + public partial class PolymorphismApiIntegration : IClassFixture + { + public PolymorphismApiIntegration(PolymorphismFixture fixture) + { + api = fixture.Api; + } + + readonly PolymorphismClient api; + + //[Fact] + //public void TestPostRopcRequest() + //{ + // var r = api.PostROPCRequst(new ROPCRequst + // { + // GrantType = "password", + // Username = "MyName", + // Password = "MyPassword" + // }); + + // Assert.Equal("password", r.GrantType); + // Assert.Equal("MyName", r.Username); + //} + + ///// + ///// Concrete in, base out + ///// + //[Fact] + //public void TestPostRopcRequest2() + //{ + // RequestBase r = api.PostROPCRequst2(new ROPCRequst + // { + // GrantType = "password", + // Username = "MyName", + // Password = "MyPassword" + // }); + + // Assert.Equal("password", r.GrantType); + // Assert.Equal("MyName", (r as ROPCRequst).Username); + //} + + //[Fact] + //public void TestPostRopcRequest3() + //{ + // ROPCRequst r = api.PostROPCRequst3(new ROPCRequst + // { + // GrantType = "password", + // Username = "MyName", + // Password = "MyPassword" + // }); + + // Assert.Equal("password", r.GrantType); + // Assert.Equal("MyName", r.Username); + //} + + //[Fact] + //public void TestPostRequestBase() + //{ + // RequestBase r = api.PostRequestBase(new ROPCRequst + // { + // GrantType = "password", + // Username = "MyName", + // Password = "MyPassword" + // }); + + // Assert.Equal("password", r.GrantType); + // var r2 = r as ROPCRequst; + // Assert.Equal("MyName", r2.Username); + //} + + + [Fact] + public async Task TestPostRopcTokenRequestAsFormDataToAuthAsync() + { + var r = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst + { + GrantType = "password", + Username = "MyName", + Password = "MyPassword" + }); + + Assert.Equal("bearer", r.TokenType); + Assert.Equal("AccessTokenString", r.AccessToken); + Assert.Equal("RefreshTokenString", r.RefreshToken); + Assert.Equal("some scope", r.Scope); + Assert.Equal(100, r.ExpiresIn); + } + + [Fact] + public async Task TestPostRefreshTokenRequestAsFormDataToAuthAsync() + { + var r = await api.PostRefreshTokenRequestAsFormDataToAuthAsync(new RefreshAccessTokenRequest + { + GrantType = "refresh_token", + RefreshToken="RefreshTokenString" + }); + + Assert.Equal("bearer", r.TokenType); + Assert.Equal("NewAccessTokenString", r.AccessToken); + Assert.Equal("NewRefreshTokenString", r.RefreshToken); + Assert.Equal("some scope", r.Scope); + Assert.Equal(100, r.ExpiresIn); + } + + //[Fact] + //public async Task TestPostROPCRequstToAuthAsync() + //{ + // var r = await api.PostROPCRequstToAuthAsync(new ROPCRequst + // { + // GrantType = "password", + // Username = "MyName", + // Password = "MyPassword" + // }); + + // Assert.Equal("bearer", r.TokenType); + // Assert.Equal("AccessTokenString", r.AccessToken); + // Assert.Equal("RefreshTokenString", r.RefreshToken); + // Assert.Equal("some scope", r.Scope); + // Assert.Equal(100, r.ExpiresIn); + //} + + + + } +} diff --git a/Tests/IntegrationTestsCore/PolymorphismFixture.cs b/Tests/IntegrationTestsCore/PolymorphismFixture.cs new file mode 100644 index 0000000..a4db324 --- /dev/null +++ b/Tests/IntegrationTestsCore/PolymorphismFixture.cs @@ -0,0 +1,25 @@ +using DemoCoreWeb.ClientApiTextJson; +using Fonlow.Testing; +using Fonlow.Text.Json.Auth; + +namespace IntegrationTests +{ + public class PolymorphismFixture : BasicHttpClient + { + public PolymorphismFixture() + { + System.Text.Json.JsonSerializerOptions jsonSerializerSettings = new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web) + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + }; + jsonSerializerSettings.Converters.Add(new TokenRequestConverter()); + + var c = TestingSettings.Instance.ServiceCommands["LaunchWebApi"]; + this.HttpClient.BaseAddress = new System.Uri(c.BaseUrl); + Api = new PolymorphismClient(HttpClient, jsonSerializerSettings); + } + + public PolymorphismClient Api { get; private set; } + } + +} diff --git a/Tests/IntegrationTestsCore/SpecialTypesFixture.cs b/Tests/IntegrationTestsCore/SpecialTypesFixture.cs deleted file mode 100644 index 45428a8..0000000 --- a/Tests/IntegrationTestsCore/SpecialTypesFixture.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Fonlow.Testing; -using System; - -namespace IntegrationTests -{ - public class SpecialTypesFixture : AuthEfHttpClientWithUsername - { - public SpecialTypesFixture() - { - Api = new DemoCoreWeb.Controllers.Client.SpecialTypes(AuthorizedClient); - } - - public DemoCoreWeb.Controllers.Client.SpecialTypes Api { get; private set; } - } -} diff --git a/Tests/IntegrationTestsCore/SuperDemoFixture.cs b/Tests/IntegrationTestsCore/SuperDemoFixture.cs deleted file mode 100644 index 9160e3a..0000000 --- a/Tests/IntegrationTestsCore/SuperDemoFixture.cs +++ /dev/null @@ -1,24 +0,0 @@ -using Fonlow.DateOnlyExtensions; -using Fonlow.Testing; -using System; - -namespace IntegrationTests -{ - public class SuperDemoFixture : AuthEfHttpClientWithUsername - { - public SuperDemoFixture() - { - var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() - { - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - }; - - jsonSerializerSettings.Converters.Add(new DateOnlyJsonConverter()); - jsonSerializerSettings.Converters.Add(new DateOnlyNullableJsonConverter()); - - Api = new DemoWebApi.Controllers.Client.SuperDemo(AuthorizedClient, jsonSerializerSettings); - } - - public DemoWebApi.Controllers.Client.SuperDemo Api { get; private set; } - } -} diff --git a/Tests/IntegrationTestsCore/TupleFixture.cs b/Tests/IntegrationTestsCore/TupleFixture.cs deleted file mode 100644 index 84297b0..0000000 --- a/Tests/IntegrationTestsCore/TupleFixture.cs +++ /dev/null @@ -1,23 +0,0 @@ -using Fonlow.DateOnlyExtensions; -using Fonlow.Testing; -using System; - -namespace IntegrationTests -{ - public class TupleFixture : AuthEfHttpClientWithUsername - { - public TupleFixture() - { - var jsonSerializerSettings = new Newtonsoft.Json.JsonSerializerSettings() - { - NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, - }; - - jsonSerializerSettings.Converters.Add(new DateOnlyJsonConverter()); - jsonSerializerSettings.Converters.Add(new DateOnlyNullableJsonConverter()); - Api = new DemoWebApi.Controllers.Client.Tuple(AuthorizedClient, jsonSerializerSettings); - } - - public DemoWebApi.Controllers.Client.Tuple Api { get; private set; } - } -} diff --git a/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs b/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs new file mode 100644 index 0000000..648553f --- /dev/null +++ b/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs @@ -0,0 +1,76 @@ +using Fonlow.Auth.Models; +using Fonlow.Text.Json.Auth; +using System.Text.Json; + +namespace ConvertersTests +{ + public class AuthModelsConvertersTests + { + [Fact] + public void TestROPCRequstSerialize() + { + ROPCRequst r = new ROPCRequst + { + GrantType = "password", + Username = "Somebody", + Password = "mypwd" + }; + + var s = System.Text.Json.JsonSerializer.Serialize(r, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Equal("{\"grant_type\":\"password\",\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null}", s); + } + + + [Fact] + public void TestROPCRequstDeserialize() + { + var s = "{\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null,\"grant_type\":\"password\"}"; + var r = System.Text.Json.JsonSerializer.Deserialize(s, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Equal("password", r.GrantType); + Assert.Equal("Somebody", r.Username); + } + + [Fact] + public void TestROPCRequstDeserializeAsRequestBase() + { + var s = "{\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null,\"grant_type\":\"password\"}"; + var r = System.Text.Json.JsonSerializer.Deserialize(s, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + Assert.Equal("password", r.GrantType); + Assert.Null(r as ROPCRequst); + } + + [Fact] + public void TestROPCRequstDeserializeAsRequestBaseWithConverter() + { + var options = new System.Text.Json.JsonSerializerOptions(new JsonSerializerOptions(JsonSerializerDefaults.Web)); + options.Converters.Add(new TokenRequestConverter()); + var s = "{\"grant_type\":\"password\",\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":\"Something somewhere\"}"; + var r = System.Text.Json.JsonSerializer.Deserialize(s, options); + Assert.Equal("password", r.GrantType); + Assert.Equal("Somebody", (r as ROPCRequst).Username); + Assert.Equal("mypwd", (r as ROPCRequst).Password); + Assert.Equal("Something somewhere", (r as ROPCRequst).Scope); + } + + [Fact] + public void TestRefreshTokenRequstDeserializeAsRequestBaseWithConverter() + { + var options = new System.Text.Json.JsonSerializerOptions(new JsonSerializerOptions(JsonSerializerDefaults.Web)); + options.Converters.Add(new TokenRequestConverter()); + var request = new RefreshAccessTokenRequest + { + GrantType = "refresh_token", + RefreshToken = "LongTokenString", + Scope = "Something", + }; + + var s = JsonSerializer.Serialize(request, options); + var r = System.Text.Json.JsonSerializer.Deserialize(s, options); + Assert.Equal("refresh_token", r.GrantType); + Assert.Equal("LongTokenString", (r as RefreshAccessTokenRequest).RefreshToken); + Assert.Equal("Something", (r as RefreshAccessTokenRequest).Scope); + } + + + } +} diff --git a/Tests/ModelsUnitTests/ModelsUnitTests.csproj b/Tests/ModelsUnitTests/ModelsUnitTests.csproj new file mode 100644 index 0000000..29d497e --- /dev/null +++ b/Tests/ModelsUnitTests/ModelsUnitTests.csproj @@ -0,0 +1,32 @@ + + + + net8.0 + enable + + false + true + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + From 61472fa489a5828b3764b7a4f739ab04c4431449 Mon Sep 17 00:00:00 2001 From: Zijian Date: Fri, 5 Jul 2024 10:18:20 +1000 Subject: [PATCH 3/5] tests ok --- Tests/AuthTests/TokenFacts.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Tests/AuthTests/TokenFacts.cs b/Tests/AuthTests/TokenFacts.cs index 3165cf2..4ffce49 100644 --- a/Tests/AuthTests/TokenFacts.cs +++ b/Tests/AuthTests/TokenFacts.cs @@ -3,10 +3,9 @@ using Fonlow.Testing; using Fonlow.WebApp.Accounts; using Microsoft.Extensions.Configuration; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using System.Diagnostics; using Xunit.Abstractions; +using System.Text.Json; namespace AuthTests { @@ -432,10 +431,11 @@ TokenResponseModel GetTokenResponseModel(HttpClient client, Action(jsonReader); + var stream = responseMessage.Content.ReadAsStream(); + return JsonSerializer.Deserialize(stream); + + //var text = responseMessage.Content.ReadAsStringAsync().Result; + //return System.Text.Json.JsonSerializer.Deserialize(text); } finally { From d0117bed64ffe55d128a014af045f6df4b137a73 Mon Sep 17 00:00:00 2001 From: Zijian Date: Sat, 6 Jul 2024 11:54:12 +1000 Subject: [PATCH 4/5] temp --- .../src/clientapi/WebApiCoreNg2ClientAuto.ts | 28 +- AuthEF.sln | 14 - Core3WebApi/Controllers/AuthController.cs | 22 +- Core3WebApi/Controllers/HeroesController.cs | 13 +- Core3WebApi/Core3WebApi.csproj | 1 - Core3WebApi/Helpers/UserTokenHelper.cs | 11 + Core3WebApi/Program.cs | 29 +- CoreWebApi.ClientApi/AuthClient.cs | 82 +++++ .../CoreWebApi.ClientApi.csproj | 4 - CoreWebApi.ClientApi/PolymorphismClient.cs | 305 ------------------ CoreWebApi.ClientApi/WebApiClientAuto.cs | 102 ++---- .../ApplicationUserManager.cs | 8 + .../TokenResponseConverter.cs | 194 +++++------ .../Fonlow.WebApp.Accounts.csproj | 1 - Fonlow.WebApp.Accounts/Models.cs | 97 ++++++ Fonlow.WebApp.Accounts/UsernameModel.cs | 3 + Tests/AuthTests/AccountFacts.cs | 3 +- Tests/AuthTests/AuthFacts.cs | 97 ++++++ Tests/AuthTests/AuthTests.csproj | 1 - Tests/AuthTests/TokenFacts.cs | 3 +- .../PolymorphismApiIntegration.cs | 133 -------- .../PolymorphismFixture.cs | 25 -- 22 files changed, 474 insertions(+), 702 deletions(-) create mode 100644 CoreWebApi.ClientApi/AuthClient.cs delete mode 100644 CoreWebApi.ClientApi/PolymorphismClient.cs create mode 100644 Fonlow.WebApp.Accounts/Models.cs create mode 100644 Tests/AuthTests/AuthFacts.cs delete mode 100644 Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs delete mode 100644 Tests/IntegrationTestsCore/PolymorphismFixture.cs diff --git a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts index 602106d..822ba2f 100644 --- a/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts +++ b/AngularHeroes/src/clientapi/WebApiCoreNg2ClientAuto.ts @@ -589,19 +589,6 @@ export namespace DemoWebApi_Controllers_Client { } } - @Injectable() - export class Polymorphism { - constructor(@Inject('baseUri') private baseUri: string = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '') + '/', private http: HttpClient) { - } - - /** - * POST api/Polymorphism - */ - authenticate(model: Fonlow_AspNetCore_OAuth2_Client.RequestBase | null, headersHandler?: () => HttpHeaders): Observable { - return this.http.post(this.baseUri + 'api/Polymorphism', JSON.stringify(model), { headers: headersHandler ? headersHandler().append('Content-Type', 'application/json;charset=UTF-8') : new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8' }) }); - } - } - /** * For testing different commbinations of parameters and returns @@ -1576,16 +1563,15 @@ export namespace Fonlow_AspNetCore_Identity_Client { } -export namespace Fonlow_AspNetCore_OAuth2_Client { - export interface AccessTokenResponse { +export namespace Fonlow_Auth_Models_Client { + export interface AccessTokenResponse extends Fonlow_Auth_Models_Client.TokenResponseBase { access_token?: string | null; expires_in?: number | null; refresh_token?: string | null; scope?: string | null; - token_type?: string | null; } - export interface RefreshAccessTokenRequest extends Fonlow_AspNetCore_OAuth2_Client.RequestBase { + export interface RefreshAccessTokenRequest extends Fonlow_Auth_Models_Client.RequestBase { refresh_token?: string | null; scope?: string | null; } @@ -1594,7 +1580,7 @@ export namespace Fonlow_AspNetCore_OAuth2_Client { grant_type?: string | null; } - export interface ROPCRequst extends Fonlow_AspNetCore_OAuth2_Client.RequestBase { + export interface ROPCRequst extends Fonlow_Auth_Models_Client.RequestBase { password?: string | null; scope?: string | null; username?: string | null; @@ -1674,6 +1660,12 @@ export namespace Fonlow_WebApp_Accounts_Client { userId?: string | null; } + export interface TokenResponseModel extends Fonlow_Auth_Models_Client.AccessTokenResponse { + connection_id?: string | null; + expires?: string | null; + username?: string | null; + } + export interface UserInfoViewModel { createdUtc?: Date | null; email?: string | null; diff --git a/AuthEF.sln b/AuthEF.sln index 31dd00a..cf49d81 100644 --- a/AuthEF.sln +++ b/AuthEF.sln @@ -60,10 +60,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PetStoreApiTests", "Tests\P EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fonlow.EntityFrameworkCore.PostgreSQL", "Fonlow.EntityFrameworkCore.PostgreSQL\Fonlow.EntityFrameworkCore.PostgreSQL.csproj", "{CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ModelsUnitTests", "Tests\ModelsUnitTests\ModelsUnitTests.csproj", "{22AC790B-B412-40BB-880F-468725DA3843}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fonlow.Auth.PayloadConverters", "Fonlow.Auth.PayloadConverters\Fonlow.Auth.PayloadConverters.csproj", "{2D30E62C-6D5A-4D77-BF2B-A477B799F338}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -146,14 +142,6 @@ Global {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Debug|Any CPU.Build.0 = Debug|Any CPU {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Release|Any CPU.ActiveCfg = Release|Any CPU {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B}.Release|Any CPU.Build.0 = Release|Any CPU - {22AC790B-B412-40BB-880F-468725DA3843}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {22AC790B-B412-40BB-880F-468725DA3843}.Debug|Any CPU.Build.0 = Debug|Any CPU - {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.ActiveCfg = Release|Any CPU - {22AC790B-B412-40BB-880F-468725DA3843}.Release|Any CPU.Build.0 = Release|Any CPU - {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2D30E62C-6D5A-4D77-BF2B-A477B799F338}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -174,8 +162,6 @@ Global {423C910B-96BB-4855-B3FB-94C060A3B8DA} = {39445712-FE9F-4406-A103-F181E9DC2233} {F91D9E0C-F235-44E1-A1DB-1213AF9663AB} = {39445712-FE9F-4406-A103-F181E9DC2233} {CE7E6D5A-E1E8-4237-BDDB-28E2B795E26B} = {03B8AB6F-9686-44AF-9AF1-6DCC6E742808} - {22AC790B-B412-40BB-880F-468725DA3843} = {39445712-FE9F-4406-A103-F181E9DC2233} - {2D30E62C-6D5A-4D77-BF2B-A477B799F338} = {03B8AB6F-9686-44AF-9AF1-6DCC6E742808} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F3EFB0EB-BFFA-4C16-B235-B121695229EF} diff --git a/Core3WebApi/Controllers/AuthController.cs b/Core3WebApi/Controllers/AuthController.cs index a004196..ef083a0 100644 --- a/Core3WebApi/Controllers/AuthController.cs +++ b/Core3WebApi/Controllers/AuthController.cs @@ -14,6 +14,7 @@ using System.Threading.Tasks; using WebApp.Utilities; using Fonlow.Auth.Models; +using System.Net.Http.Headers; namespace WebApp.Controllers { @@ -71,18 +72,19 @@ public async Task> Authenticate([FromForm] Requ } var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); - var newLoginConnectionId = Guid.NewGuid(); - return await tokenHelper.GenerateJwtToken(user, ropcRequest.Username, newLoginConnectionId); + //var newLoginConnectionId = Guid.NewGuid(); + return await tokenHelper.GenerateJwtToken(user, ropcRequest.Username, Guid.Empty); //todo: some apps may need to deal with scope } - else if (model is RefreshAccessTokenRequest) + else if (model is RefreshAccessTokenRequest refreshAccessTokenRequest) { - //RefreshAccessTokenRequest refreshAccessTokenRequest = model as RefreshAccessTokenRequest; - //var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); - //var tokenTextExisting = await tokenHelper.MatchToken(user, "RefreshToken", refreshAccessTokenRequest.RefreshTokent, connectionId); - //if (!tokenTextExisting) - //{ - // return StatusCode(401, new { message = "Invalid to retrieve token through refreshToken" }); // message may be omitted in prod build, to avoid exposing implementation details. - //} + ClaimsPrincipal userClaimsPrincipal = Request.HttpContext.User; + var username = userClaimsPrincipal.Identity.Name; + var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); + var tokenTextExisting = await tokenHelper.MatchToken(userClaimsPrincipal, "RefreshToken", refreshAccessTokenRequest.RefreshToken, Guid.Empty); + if (!tokenTextExisting) + { + return StatusCode(401, new { message = "Invalid to retrieve token through refreshToken" }); // message may be omitted in prod build, to avoid exposing implementation details. + } //return await tokenHelper.GenerateJwtToken(user, username, connectionId); //the old refresh token is removed } diff --git a/Core3WebApi/Controllers/HeroesController.cs b/Core3WebApi/Controllers/HeroesController.cs index 6804a66..4491ddf 100644 --- a/Core3WebApi/Controllers/HeroesController.cs +++ b/Core3WebApi/Controllers/HeroesController.cs @@ -7,6 +7,9 @@ using System.Threading.Tasks; using Fonlow.DemoApp; using Microsoft.AspNetCore.Authorization; +using System.Security.Claims; +using Microsoft.AspNetCore.Identity; +using Fonlow.AspNetCore.Identity; namespace DemoWebApi.Controllers { @@ -19,6 +22,12 @@ namespace DemoWebApi.Controllers [Authorize(AuthenticationSchemes = ApiConstants.DefaultAuthenticationScheme)] public class HeroesController : ControllerBase { + public HeroesController(ApplicationUserManager userManager) + { + this.userManager= userManager; + } + + readonly ApplicationUserManager userManager; /// /// Get all heroes. /// @@ -66,8 +75,10 @@ public Hero PostWithQuery([FromQuery] string name)//.net core difference: requir } [HttpPost] - public Hero Post([FromBody] string name)//.net core difference: requires explicit decorattion + public async Task Post([FromBody] string name)//.net core difference: requires explicit decorattion { + ClaimsPrincipal userClaimsPrincipal = Request.HttpContext.User; + var user = await userManager.GetUserAsync(userClaimsPrincipal); var max = HeroesData.Instance.Dic.Keys.Max(); var hero = new Hero { Id = max + 1, Name = name }; _ = HeroesData.Instance.Dic.TryAdd(max + 1, hero); diff --git a/Core3WebApi/Core3WebApi.csproj b/Core3WebApi/Core3WebApi.csproj index e685f5e..31161b1 100644 --- a/Core3WebApi/Core3WebApi.csproj +++ b/Core3WebApi/Core3WebApi.csproj @@ -22,7 +22,6 @@ - diff --git a/Core3WebApi/Helpers/UserTokenHelper.cs b/Core3WebApi/Helpers/UserTokenHelper.cs index 76be751..060b53a 100644 --- a/Core3WebApi/Helpers/UserTokenHelper.cs +++ b/Core3WebApi/Helpers/UserTokenHelper.cs @@ -68,6 +68,17 @@ public async Task MatchToken(ApplicationUser user, string purpose, string return tokenValue == storedToken; } + public async Task MatchToken(ClaimsPrincipal userClaimsPrincipal, string purpose, string tokenValue, Guid connectionId) + { + var user = await userManager.GetUserAsync(userClaimsPrincipal); + if (user==null){ + return false; + } + //var isValid = await userManager.VerifyUserTokenAsync(user, authSettings.TokenProviderName, "RefreshToken", tokenValue); probably no need to call this to avoid mix token purpose usages? + //and can not handle the expiry of refresh token, or any token needs to be expired. Also, cross machines issues as documented on https://stackoverflow.com/questions/51966010/identity-framework-generateusertoken-validation-issue + return await MatchToken(user, purpose, tokenValue, connectionId); + } + /// /// Generate token and refreshToken. /// The claim is based on the roles of the user. diff --git a/Core3WebApi/Program.cs b/Core3WebApi/Program.cs index 35c1ecc..406dc9b 100644 --- a/Core3WebApi/Program.cs +++ b/Core3WebApi/Program.cs @@ -101,9 +101,9 @@ ValidAudience = authSettings.Audience, ValidIssuer = authSettings.Issuer, IssuerSigningKey = issuerSigningKey, - #if DEBUG - ClockSkew=TimeSpan.FromSeconds(2), //Default is 300 seconds. This is for testing the correctness of the auth protocol implementation between C/S. - #endif +#if DEBUG + ClockSkew = TimeSpan.FromSeconds(2), //Default is 300 seconds. This is for testing the correctness of the auth protocol implementation between C/S. +#endif }; // Thanks to https://dotnetdetail.net/asp-net-core-3-0-web-api-token-based-authentication-example-using-jwt-in-vs2019/ }); @@ -129,7 +129,12 @@ dbEngineDbContext.ConnectDatabase(dcob, identityConnectionString); // called by runtime everytime an instance of ApplicationDbContext is created. }); -builder.Services.AddIdentity() +builder.Services.AddIdentity( + options => + { + options.ClaimsIdentity.UserNameClaimType = "UserID"; + } + ) .AddEntityFrameworkStores() .AddUserManager() .AddDefaultTokenProviders() @@ -144,14 +149,14 @@ } else { -// //Only release build support https redirection. -//#if RELEASE -// if (useHttps) // for locally running app, no need to have https. -// { -// app.UseHttpsRedirection(); -// app.UseHsts();//https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-6.0 -// } -//#endif + // //Only release build support https redirection. + //#if RELEASE + // if (useHttps) // for locally running app, no need to have https. + // { + // app.UseHttpsRedirection(); + // app.UseHsts();//https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-6.0 + // } + //#endif } app.UseAuthentication(); app.UseAuthorization(); diff --git a/CoreWebApi.ClientApi/AuthClient.cs b/CoreWebApi.ClientApi/AuthClient.cs new file mode 100644 index 0000000..82060f2 --- /dev/null +++ b/CoreWebApi.ClientApi/AuthClient.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using Fonlow.Net.Http; + +namespace Fonlow.Auth.Client +{ + public class AuthClient + { + + private System.Net.Http.HttpClient client; + + private JsonSerializerOptions jsonSerializerSettings; + + public AuthClient(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings = null) + { + if (client == null) + throw new ArgumentNullException(nameof(client), "Null HttpClient."); + + if (client.BaseAddress == null) + throw new ArgumentNullException(nameof(client), "HttpClient has no BaseAddress"); + + this.client = client; + this.jsonSerializerSettings = jsonSerializerSettings; + } + + /// + /// Post ROPC request as FormData to auth token endpoint. + /// + /// + /// + /// + public async Task PostRopcTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.Client.ROPCRequst model, Action handleHeaders = null) + { + var requestUri = "token"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var pairs = new KeyValuePair[] + { + new KeyValuePair( "grant_type", model.GrantType ), + new KeyValuePair( "username", model.Username ), + new KeyValuePair ( "password", model.Password ) + }; + var content = new FormUrlEncodedContent(pairs); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + using var responseMessage = await client.SendAsync(httpRequestMessage); + responseMessage.EnsureSuccessStatusCodeEx(); + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + + /// + /// Post refresh token request as FormData to auth token endpoint + /// + /// + /// + /// + public async Task PostRefreshTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.Client.RefreshAccessTokenRequest model, Action handleHeaders = null) + { + var requestUri = "token"; + using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); + var pairs = new KeyValuePair[] + { + new KeyValuePair( "grant_type", model.GrantType ), + new KeyValuePair( "refresh_token", model.RefreshToken ), + new KeyValuePair ( "scope", model.Scope ) + }; + var content = new FormUrlEncodedContent(pairs); + httpRequestMessage.Content = content; + handleHeaders?.Invoke(httpRequestMessage.Headers); + using var responseMessage = await client.SendAsync(httpRequestMessage); + responseMessage.EnsureSuccessStatusCodeEx(); + var stream = await responseMessage.Content.ReadAsStreamAsync(); + return JsonSerializer.Deserialize(stream, jsonSerializerSettings); + } + } + +} diff --git a/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj b/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj index da11cea..f68fb9c 100644 --- a/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj +++ b/CoreWebApi.ClientApi/CoreWebApi.ClientApi.csproj @@ -8,8 +8,4 @@ - - - - diff --git a/CoreWebApi.ClientApi/PolymorphismClient.cs b/CoreWebApi.ClientApi/PolymorphismClient.cs deleted file mode 100644 index a1931da..0000000 --- a/CoreWebApi.ClientApi/PolymorphismClient.cs +++ /dev/null @@ -1,305 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Net.Http; -using System.Text.Json; -using System.Text.Json.Serialization; -using Fonlow.Net.Http; - -namespace DemoCoreWeb.ClientApiTextJson -{ - public partial class PolymorphismClient - { - - private System.Net.Http.HttpClient client; - - private JsonSerializerOptions jsonSerializerSettings; - - public PolymorphismClient(System.Net.Http.HttpClient client, JsonSerializerOptions jsonSerializerSettings = null) - { - if (client == null) - throw new ArgumentNullException(nameof(client), "Null HttpClient."); - - if (client.BaseAddress == null) - throw new ArgumentNullException(nameof(client), "HttpClient has no BaseAddress"); - - this.client = client; - this.jsonSerializerSettings = jsonSerializerSettings; - } - - public async Task PostRopcTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var pairs = new KeyValuePair[] - { - new KeyValuePair( "grant_type", model.GrantType ), - new KeyValuePair( "username", model.Username ), - new KeyValuePair ( "password", model.Password ) - }; - var content = new FormUrlEncodedContent(pairs); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - public async Task PostRefreshTokenRequestAsFormDataToAuthAsync(Fonlow.Auth.Models.RefreshAccessTokenRequest model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var pairs = new KeyValuePair[] - { - new KeyValuePair( "grant_type", model.GrantType ), - new KeyValuePair( "RefreshTokenString", model.RefreshToken ), - new KeyValuePair ( "something", model.Scope ) - }; - var content = new FormUrlEncodedContent(pairs); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst - /// - public async Task PostROPCRequstToAuthAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - - - /// - /// POST api/Polymorphism/PostRequestBase - /// - public async Task PostRequestBaseAsync(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostRequestBase"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostRequestBase - /// - public Fonlow.Auth.Models.RequestBase PostRequestBase(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostRequestBase"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = client.Send(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = responseMessage.Content.ReadAsStream(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst - /// - public async Task PostROPCRequstAsync(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst - /// - public Fonlow.Auth.Models.ROPCRequst PostROPCRequst(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = client.Send(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = responseMessage.Content.ReadAsStream(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst2 - /// - public async Task PostROPCRequst2Async(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst2"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst2 - /// - public Fonlow.Auth.Models.RequestBase PostROPCRequst2(Fonlow.Auth.Models.ROPCRequst model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst2"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = client.Send(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = responseMessage.Content.ReadAsStream(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst3 - /// - public async Task PostROPCRequst3Async(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst3"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism/PostROPCRequst3 - /// - public Fonlow.Auth.Models.ROPCRequst PostROPCRequst3(Fonlow.Auth.Models.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism/PostROPCRequst3"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = client.Send(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = responseMessage.Content.ReadAsStream(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - } - -} diff --git a/CoreWebApi.ClientApi/WebApiClientAuto.cs b/CoreWebApi.ClientApi/WebApiClientAuto.cs index e1dab24..a573afe 100644 --- a/CoreWebApi.ClientApi/WebApiClientAuto.cs +++ b/CoreWebApi.ClientApi/WebApiClientAuto.cs @@ -3012,74 +3012,6 @@ public System.Net.Http.HttpResponseMessage Index(Action - /// POST api/Polymorphism - /// - public async Task AuthenticateAsync(Fonlow.AspNetCore.OAuth2.Client.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = await client.SendAsync(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = await responseMessage.Content.ReadAsStreamAsync(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - - /// - /// POST api/Polymorphism - /// - public Fonlow.AspNetCore.OAuth2.Client.RequestBase Authenticate(Fonlow.AspNetCore.OAuth2.Client.RequestBase model, Action handleHeaders = null) - { - var requestUri = "api/Polymorphism"; - using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); - var content = System.Net.Http.Json.JsonContent.Create(model, mediaType: null, jsonSerializerSettings); - httpRequestMessage.Content = content; - handleHeaders?.Invoke(httpRequestMessage.Headers); - var responseMessage = client.Send(httpRequestMessage); - try - { - responseMessage.EnsureSuccessStatusCodeEx(); - if (responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent) { return null; } - var stream = responseMessage.Content.ReadAsStream(); - return JsonSerializer.Deserialize(stream, jsonSerializerSettings); - } - finally - { - responseMessage.Dispose(); - } - } - } - /// /// For testing different commbinations of parameters and returns /// Authorize: Bearer @@ -7867,12 +7799,12 @@ public class UsernameModel : object public string Username { get; set; } } } -namespace Fonlow.AspNetCore.OAuth2.Client +namespace Fonlow.Auth.Models.Client { [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] - public class AccessTokenResponse : object + public class AccessTokenResponse : Fonlow.Auth.Models.Client.TokenResponseBase { [System.ComponentModel.DataAnnotations.Required()] @@ -7891,21 +7823,16 @@ public class AccessTokenResponse : object [System.Runtime.Serialization.DataMember()] public string Scope { get; set; } - - [System.ComponentModel.DataAnnotations.Required()] - [System.Runtime.Serialization.DataMember(Name="token_type")] - [System.Text.Json.Serialization.JsonPropertyName("token_type")] - public string TokenType { get; set; } } [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] - public class RefreshAccessTokenRequest : Fonlow.AspNetCore.OAuth2.Client.RequestBase + public class RefreshAccessTokenRequest : Fonlow.Auth.Models.Client.RequestBase { [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="refresh_token")] [System.Text.Json.Serialization.JsonPropertyName("refresh_token")] - public string RefreshTokent { get; set; } + public string RefreshToken { get; set; } [System.Runtime.Serialization.DataMember()] public string Scope { get; set; } @@ -7922,7 +7849,7 @@ public class RequestBase : object } [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] - public class ROPCRequst : Fonlow.AspNetCore.OAuth2.Client.RequestBase + public class ROPCRequst : Fonlow.Auth.Models.Client.RequestBase { [System.ComponentModel.DataAnnotations.Required()] @@ -8123,6 +8050,25 @@ public class SetUserPasswordBindingModel : Fonlow.WebApp.Accounts.Client.SetPass public string UserId { get; set; } } + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] + public class TokenResponseModel : Fonlow.Auth.Models.Client.AccessTokenResponse + { + + [System.Runtime.Serialization.DataMember(Name="connection_id")] + [System.Text.Json.Serialization.JsonPropertyName("connection_id")] + public System.Guid ConnectionId { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + [System.Text.Json.Serialization.JsonPropertyName("expires")] + public string Expires { get; set; } + + [System.ComponentModel.DataAnnotations.Required()] + [System.Runtime.Serialization.DataMember()] + [System.Text.Json.Serialization.JsonPropertyName("username")] + public string Username { get; set; } + } + [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] public class UserInfoViewModel : object { diff --git a/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs b/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs index d769e50..f21cc08 100644 --- a/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs +++ b/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using System.Security.Claims; namespace Fonlow.AspNetCore.Identity { @@ -23,5 +24,12 @@ public Task FindByIdAsync(Guid userId) { return base.FindByIdAsync(userId.ToString()); } + + //public override Task GetUserAsync(ClaimsPrincipal principal) + //{ + // ArgumentNullException.ThrowIfNull(principal); + // var id = GetUserId(principal); + // return id == null ? Task.FromResult(null) : FindByIdAsync(id); + //} } } \ No newline at end of file diff --git a/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs b/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs index 131fe15..4720145 100644 --- a/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs +++ b/Fonlow.Auth.PayloadConverters/TokenResponseConverter.cs @@ -1,109 +1,109 @@ -using Fonlow.Auth.Models; -using System.Text.Json; -using System.Text.Json.Serialization; +//using Fonlow.Auth.Models; +//using System.Text.Json; +//using System.Text.Json.Serialization; -namespace Fonlow.Text.Json.Auth -{ - public sealed class TokenResponseConverter : JsonConverter - { - public override bool HandleNull => true; +//namespace Fonlow.Text.Json.Auth +//{ +// public sealed class TokenResponseConverter : JsonConverter +// { +// public override bool HandleNull => true; - public override void Write(Utf8JsonWriter writer, TokenResponseBase value, JsonSerializerOptions options) - { - writer.WriteStartObject(); - writer.WriteString("token_type", value.TokenType); - switch (value.TokenType) - { - case "bearer": - case "Bearer": - AccessTokenResponse accessTokenResponse = value as AccessTokenResponse; - writer.WriteString("access_token", accessTokenResponse.AccessToken); - writer.WriteNumber("expires_in", Convert.ToDecimal(accessTokenResponse.ExpiresIn)); - if (!string.IsNullOrWhiteSpace(accessTokenResponse.RefreshToken)) - { - writer.WriteString("refresh_token", accessTokenResponse.RefreshToken); - } +// public override void Write(Utf8JsonWriter writer, TokenResponseBase value, JsonSerializerOptions options) +// { +// writer.WriteStartObject(); +// writer.WriteString("token_type", value.TokenType); +// switch (value.TokenType) +// { +// case "bearer": +// case "Bearer": +// AccessTokenResponse accessTokenResponse = value as AccessTokenResponse; +// writer.WriteString("access_token", accessTokenResponse.AccessToken); +// writer.WriteNumber("expires_in", Convert.ToDecimal(accessTokenResponse.ExpiresIn)); +// if (!string.IsNullOrWhiteSpace(accessTokenResponse.RefreshToken)) +// { +// writer.WriteString("refresh_token", accessTokenResponse.RefreshToken); +// } - if (!string.IsNullOrWhiteSpace(accessTokenResponse.Scope)) - { - writer.WriteString("scope", accessTokenResponse.Scope); - } - break; - default: - throw new NotSupportedException(); - } +// if (!string.IsNullOrWhiteSpace(accessTokenResponse.Scope)) +// { +// writer.WriteString("scope", accessTokenResponse.Scope); +// } +// break; +// default: +// throw new NotSupportedException(); +// } - writer.WriteEndObject(); - } +// writer.WriteEndObject(); +// } - public override TokenResponseBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType != JsonTokenType.StartObject) - { - throw new JsonException(); - } +// public override TokenResponseBase Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) +// { +// if (reader.TokenType != JsonTokenType.StartObject) +// { +// throw new JsonException(); +// } - reader.Read(); - if (reader.TokenType != JsonTokenType.PropertyName) - { - throw new JsonException(); - } +// reader.Read(); +// if (reader.TokenType != JsonTokenType.PropertyName) +// { +// throw new JsonException(); +// } - string propertyName = reader.GetString(); - if (propertyName != "token_type") - { - throw new JsonException(); - } +// string propertyName = reader.GetString(); +// if (propertyName != "token_type") +// { +// throw new JsonException(); +// } - reader.Read(); - if (reader.TokenType != JsonTokenType.String) - { - throw new JsonException(); - } +// reader.Read(); +// if (reader.TokenType != JsonTokenType.String) +// { +// throw new JsonException(); +// } - var typeDiscriminator = reader.GetString(); +// var typeDiscriminator = reader.GetString(); - switch (typeDiscriminator) - { - case "bearer": - case "Bearer": - var accessTokenResponse = new AccessTokenResponse(); - accessTokenResponse.TokenType = typeDiscriminator; - while (reader.Read()) - { - if (reader.TokenType == JsonTokenType.EndObject) - { - return accessTokenResponse; - } +// switch (typeDiscriminator) +// { +// case "bearer": +// case "Bearer": +// var accessTokenResponse = new AccessTokenResponse(); +// accessTokenResponse.TokenType = typeDiscriminator; +// while (reader.Read()) +// { +// if (reader.TokenType == JsonTokenType.EndObject) +// { +// return accessTokenResponse; +// } - if (reader.TokenType == JsonTokenType.PropertyName) - { - propertyName = reader.GetString(); - if (reader.Read()) - { - switch (propertyName) - { - case "access_token": - accessTokenResponse.AccessToken = reader.GetString(); - break; - case "refresh_token": - accessTokenResponse.AccessToken = reader.GetString(); - break; - case "expires_in": - accessTokenResponse.ExpiresIn = reader.GetInt32(); - break; - case "scope": - accessTokenResponse.Scope = reader.GetString(); - break; - } - } - } - } +// if (reader.TokenType == JsonTokenType.PropertyName) +// { +// propertyName = reader.GetString(); +// if (reader.Read()) +// { +// switch (propertyName) +// { +// case "access_token": +// accessTokenResponse.AccessToken = reader.GetString(); +// break; +// case "refresh_token": +// accessTokenResponse.AccessToken = reader.GetString(); +// break; +// case "expires_in": +// accessTokenResponse.ExpiresIn = reader.GetInt32(); +// break; +// case "scope": +// accessTokenResponse.Scope = reader.GetString(); +// break; +// } +// } +// } +// } - return accessTokenResponse; - default: - throw new JsonException(); - } - } - } -} +// return accessTokenResponse; +// default: +// throw new JsonException(); +// } +// } +// } +//} diff --git a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj index 7798741..de1a572 100644 --- a/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj +++ b/Fonlow.WebApp.Accounts/Fonlow.WebApp.Accounts.csproj @@ -29,7 +29,6 @@ - diff --git a/Fonlow.WebApp.Accounts/Models.cs b/Fonlow.WebApp.Accounts/Models.cs new file mode 100644 index 0000000..f27b556 --- /dev/null +++ b/Fonlow.WebApp.Accounts/Models.cs @@ -0,0 +1,97 @@ +using System.ComponentModel.DataAnnotations; +using System.Runtime.Serialization; +using System.Text.Json.Serialization; + +namespace Fonlow.Auth.Models +{ +// Data contract attbibutes are basically for NewtonSoft.Json which respects these attributes + //[JsonPolymorphic(TypeDiscriminatorPropertyName = "grant_type")] + //[JsonDerivedType(typeof(ROPCRequst), "password")] + //[JsonDerivedType(typeof(RefreshAccessTokenRequest), "refresh_token")] + [DataContract] + public class RequestBase + { + [Required] + [JsonPropertyName("grant_type")] + [JsonPropertyOrder(-10)] + [DataMember(Name = "grant_type")] + public string GrantType { get; set; } + } + + /// + /// Section 4.3 and 4.3.2. + /// GrantType must be Value MUST be set to "password". + /// + [DataContract] + public class ROPCRequst : RequestBase + { + [Required] + [DataMember] + public string Username { get; set; } + + [Required] + [DataMember] + public string Password { get; set; } + + [DataMember] + public string Scope { get; set; } + + } + + /// + /// Section 6 + /// Grant type MUST be set to "refresh_token". + /// + [DataContract] + public class RefreshAccessTokenRequest : RequestBase + { + [Required] + [JsonPropertyName("refresh_token")] + [DataMember(Name = "refresh_token")] + public string RefreshToken { get; set; } + + [DataMember] + public string Scope { get; set; } + } + + [DataContract] + public abstract class TokenResponseBase + { + /// + /// Such as bearer or Bearer + /// + [Required] + [JsonPropertyOrder(-10)] + [JsonPropertyName("token_type")] + [DataMember(Name = "token_type")] + public string TokenType { get; set; } + } + + /// + /// Section 5.1 + /// + [DataContract] + public class AccessTokenResponse : TokenResponseBase + { + [JsonPropertyName("access_token")] + [DataMember(Name = "access_token")] + [Required] + public string AccessToken { get; set; } + + /// + /// In the spec, it is recommended, however, it is bad in practice if not required. + /// + [JsonPropertyName("expires_in")] + [DataMember(Name = "expires_in")] + [Required] + public int ExpiresIn { get; set; } + + [JsonPropertyName("refresh_token")] + [DataMember(Name = "refresh_token")] + public string RefreshToken { get; set; } + + [DataMember] + public string Scope { get; set; } + } + +} diff --git a/Fonlow.WebApp.Accounts/UsernameModel.cs b/Fonlow.WebApp.Accounts/UsernameModel.cs index e244548..e0867c2 100644 --- a/Fonlow.WebApp.Accounts/UsernameModel.cs +++ b/Fonlow.WebApp.Accounts/UsernameModel.cs @@ -9,9 +9,11 @@ namespace Fonlow.WebApp.Accounts /// https://datatracker.ietf.org/doc/html/rfc7519 JWT /// https://www.ietf.org/rfc/rfc6749.txt, The OAuth 2.0 Authorization Framework /// + [DataContract] public class TokenResponseModel : Fonlow.Auth.Models.AccessTokenResponse { [JsonPropertyName("username")] + [DataMember] [Required] public string Username { get; set; } @@ -22,6 +24,7 @@ public class TokenResponseModel : Fonlow.Auth.Models.AccessTokenResponse /// For human readable. The app codes generaly use expires_in /// [JsonPropertyName("expires")] + [DataMember] [Required] public string Expires { get; set; } diff --git a/Tests/AuthTests/AccountFacts.cs b/Tests/AuthTests/AccountFacts.cs index c38dbf1..784d714 100644 --- a/Tests/AuthTests/AccountFacts.cs +++ b/Tests/AuthTests/AccountFacts.cs @@ -1,12 +1,13 @@ using DemoWebApi.Controllers.Client; using Fonlow.Net.Http; using Fonlow.Testing; -using Fonlow.WebApp.Accounts; + using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Diagnostics; using System.Net.WebSockets; using Xunit.Abstractions; +using Fonlow.WebApp.Accounts.Client; namespace AuthTests { diff --git a/Tests/AuthTests/AuthFacts.cs b/Tests/AuthTests/AuthFacts.cs new file mode 100644 index 0000000..759d7fc --- /dev/null +++ b/Tests/AuthTests/AuthFacts.cs @@ -0,0 +1,97 @@ +using Fonlow.Auth.Client; +using Fonlow.Testing; +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Fonlow.Auth.Models.Client; + +namespace AuthTests +{ + public class AuthTestsFixture : BasicHttpClient + { + public AuthTestsFixture() + { + var c = TestingSettings.Instance.ServiceCommands["LaunchIdentityWebApi"]; + this.HttpClient.BaseAddress = new System.Uri(c.BaseUrl); + + IConfiguration config = new ConfigurationBuilder() + .AddJsonFile("appsettings.json") + .Build(); + + ClockSkewMilliseconds = int.Parse(config["ClockSkewSeconds"]) * 1000; + System.Text.Json.JsonSerializerOptions jsonSerializerSettings = new System.Text.Json.JsonSerializerOptions() + { + DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, + PropertyNameCaseInsensitive = true, + NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.AllowReadingFromString, // newtonsoft.json along with converters may return long and int128 as string + }; + + Api = new AuthClient(HttpClient, jsonSerializerSettings); + BaseUrl = c.BaseUrl; + } + + public int ClockSkewMilliseconds { get; private set; } + + public AuthClient Api { get; private set; } + public string BaseUrl { get; private set; } + } + + [Collection(IntegrationTests.TestConstants.LaunchWebApiAndInit)] + public class AuthFacts : IClassFixture + { + public AuthFacts(AuthTestsFixture fixture) + { + api = fixture.Api; + baseUrl = fixture.BaseUrl; + } + + readonly AuthClient api; + readonly string baseUrl; + [Fact] + public async Task TestPostRopcTokenRequestAsFormDataToAuthAsync() + { + var r = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst + { + GrantType = "password", + Username = "admin", + Password = "Pppppp*8" + }); + + Assert.Equal("bearer", r.TokenType, true); + Assert.NotNull(r.AccessToken); + Assert.NotNull(r.RefreshToken); + //Assert.Equal("some scope", r.Scope); + Assert.True(r.ExpiresIn > 0); + } + + [Fact] + public async Task TestPostRefreshTokenRequestAsFormDataToAuthAsync() + { + var ra = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst + { + GrantType = "password", + Username = "admin", + Password = "Pppppp*8" + }); + + HttpClient client = new HttpClient(); + client.BaseAddress = new Uri(baseUrl); + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ra.AccessToken); + AuthClient authClient = new AuthClient(client); + var r = await authClient.PostRefreshTokenRequestAsFormDataToAuthAsync(new RefreshAccessTokenRequest + { + GrantType = "refresh_token", + RefreshToken = "RefreshTokenString" + }); + + Assert.Equal("bearer", r.TokenType, true); + Assert.NotNull(r.AccessToken); + Assert.NotNull(r.RefreshToken); + //Assert.Equal("some scope", r.Scope); + Assert.True(r.ExpiresIn > 0); + } + } +} diff --git a/Tests/AuthTests/AuthTests.csproj b/Tests/AuthTests/AuthTests.csproj index 79d14b4..6cb9ade 100644 --- a/Tests/AuthTests/AuthTests.csproj +++ b/Tests/AuthTests/AuthTests.csproj @@ -37,7 +37,6 @@ - diff --git a/Tests/AuthTests/TokenFacts.cs b/Tests/AuthTests/TokenFacts.cs index 4ffce49..23724df 100644 --- a/Tests/AuthTests/TokenFacts.cs +++ b/Tests/AuthTests/TokenFacts.cs @@ -1,11 +1,12 @@ using DemoWebApi.Controllers.Client; using Fonlow.Net.Http; using Fonlow.Testing; -using Fonlow.WebApp.Accounts; using Microsoft.Extensions.Configuration; using System.Diagnostics; using Xunit.Abstractions; using System.Text.Json; +using Fonlow.Auth.Models.Client; +using Fonlow.WebApp.Accounts.Client; namespace AuthTests { diff --git a/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs b/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs deleted file mode 100644 index b4971fe..0000000 --- a/Tests/IntegrationTestsCore/PolymorphismApiIntegration.cs +++ /dev/null @@ -1,133 +0,0 @@ -using Xunit; -using IntegrationTests; -using Fonlow.Auth.Models; -using DemoCoreWeb.ClientApiTextJson; -using System.Threading.Tasks; - -namespace TextJsonIntegrationTests -{ - [Collection(TestConstants.LaunchWebApiAndInit)] - public partial class PolymorphismApiIntegration : IClassFixture - { - public PolymorphismApiIntegration(PolymorphismFixture fixture) - { - api = fixture.Api; - } - - readonly PolymorphismClient api; - - //[Fact] - //public void TestPostRopcRequest() - //{ - // var r = api.PostROPCRequst(new ROPCRequst - // { - // GrantType = "password", - // Username = "MyName", - // Password = "MyPassword" - // }); - - // Assert.Equal("password", r.GrantType); - // Assert.Equal("MyName", r.Username); - //} - - ///// - ///// Concrete in, base out - ///// - //[Fact] - //public void TestPostRopcRequest2() - //{ - // RequestBase r = api.PostROPCRequst2(new ROPCRequst - // { - // GrantType = "password", - // Username = "MyName", - // Password = "MyPassword" - // }); - - // Assert.Equal("password", r.GrantType); - // Assert.Equal("MyName", (r as ROPCRequst).Username); - //} - - //[Fact] - //public void TestPostRopcRequest3() - //{ - // ROPCRequst r = api.PostROPCRequst3(new ROPCRequst - // { - // GrantType = "password", - // Username = "MyName", - // Password = "MyPassword" - // }); - - // Assert.Equal("password", r.GrantType); - // Assert.Equal("MyName", r.Username); - //} - - //[Fact] - //public void TestPostRequestBase() - //{ - // RequestBase r = api.PostRequestBase(new ROPCRequst - // { - // GrantType = "password", - // Username = "MyName", - // Password = "MyPassword" - // }); - - // Assert.Equal("password", r.GrantType); - // var r2 = r as ROPCRequst; - // Assert.Equal("MyName", r2.Username); - //} - - - [Fact] - public async Task TestPostRopcTokenRequestAsFormDataToAuthAsync() - { - var r = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst - { - GrantType = "password", - Username = "MyName", - Password = "MyPassword" - }); - - Assert.Equal("bearer", r.TokenType); - Assert.Equal("AccessTokenString", r.AccessToken); - Assert.Equal("RefreshTokenString", r.RefreshToken); - Assert.Equal("some scope", r.Scope); - Assert.Equal(100, r.ExpiresIn); - } - - [Fact] - public async Task TestPostRefreshTokenRequestAsFormDataToAuthAsync() - { - var r = await api.PostRefreshTokenRequestAsFormDataToAuthAsync(new RefreshAccessTokenRequest - { - GrantType = "refresh_token", - RefreshToken="RefreshTokenString" - }); - - Assert.Equal("bearer", r.TokenType); - Assert.Equal("NewAccessTokenString", r.AccessToken); - Assert.Equal("NewRefreshTokenString", r.RefreshToken); - Assert.Equal("some scope", r.Scope); - Assert.Equal(100, r.ExpiresIn); - } - - //[Fact] - //public async Task TestPostROPCRequstToAuthAsync() - //{ - // var r = await api.PostROPCRequstToAuthAsync(new ROPCRequst - // { - // GrantType = "password", - // Username = "MyName", - // Password = "MyPassword" - // }); - - // Assert.Equal("bearer", r.TokenType); - // Assert.Equal("AccessTokenString", r.AccessToken); - // Assert.Equal("RefreshTokenString", r.RefreshToken); - // Assert.Equal("some scope", r.Scope); - // Assert.Equal(100, r.ExpiresIn); - //} - - - - } -} diff --git a/Tests/IntegrationTestsCore/PolymorphismFixture.cs b/Tests/IntegrationTestsCore/PolymorphismFixture.cs deleted file mode 100644 index a4db324..0000000 --- a/Tests/IntegrationTestsCore/PolymorphismFixture.cs +++ /dev/null @@ -1,25 +0,0 @@ -using DemoCoreWeb.ClientApiTextJson; -using Fonlow.Testing; -using Fonlow.Text.Json.Auth; - -namespace IntegrationTests -{ - public class PolymorphismFixture : BasicHttpClient - { - public PolymorphismFixture() - { - System.Text.Json.JsonSerializerOptions jsonSerializerSettings = new System.Text.Json.JsonSerializerOptions(System.Text.Json.JsonSerializerDefaults.Web) - { - DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull, - }; - jsonSerializerSettings.Converters.Add(new TokenRequestConverter()); - - var c = TestingSettings.Instance.ServiceCommands["LaunchWebApi"]; - this.HttpClient.BaseAddress = new System.Uri(c.BaseUrl); - Api = new PolymorphismClient(HttpClient, jsonSerializerSettings); - } - - public PolymorphismClient Api { get; private set; } - } - -} From c701b9f3810213a8e84e22e3ad343f05c37081c5 Mon Sep 17 00:00:00 2001 From: Zijian Date: Sun, 7 Jul 2024 16:00:56 +1000 Subject: [PATCH 5/5] ok --- Core3WebApi/Controllers/AuthController.cs | 31 +++-- Core3WebApi/Controllers/HeroesController.cs | 2 - .../Controllers/PolymorphismController.cs | 20 +-- .../Helpers/OAuth2RequestBinderProvider.cs | 2 +- Core3WebApi/Helpers/UserTokenHelper.cs | 28 ++-- CoreWebApi.ClientApi/AuthClient.cs | 6 +- CoreWebApi.ClientApi/WebApiClientAuto.cs | 12 +- .../ApplicationUserManager.cs | 7 - Fonlow.WebApp.Accounts/Models.cs | 12 +- Tests/AuthRemoteTests/AccountFacts.cs | 16 +-- Tests/AuthRemoteTests/TokenFacts.cs | 118 ++++++++-------- Tests/AuthTests/AccountFacts.cs | 16 +-- Tests/AuthTests/AuthFacts.cs | 26 ++-- Tests/AuthTests/TokenFacts.cs | 128 +++++++++--------- .../AuthModelsConvertersTests.cs | 76 ----------- Tests/ModelsUnitTests/ModelsUnitTests.csproj | 32 ----- 16 files changed, 214 insertions(+), 318 deletions(-) delete mode 100644 Tests/ModelsUnitTests/AuthModelsConvertersTests.cs delete mode 100644 Tests/ModelsUnitTests/ModelsUnitTests.csproj diff --git a/Core3WebApi/Controllers/AuthController.cs b/Core3WebApi/Controllers/AuthController.cs index ef083a0..2e764e3 100644 --- a/Core3WebApi/Controllers/AuthController.cs +++ b/Core3WebApi/Controllers/AuthController.cs @@ -77,16 +77,29 @@ public async Task> Authenticate([FromForm] Requ } else if (model is RefreshAccessTokenRequest refreshAccessTokenRequest) { - ClaimsPrincipal userClaimsPrincipal = Request.HttpContext.User; - var username = userClaimsPrincipal.Identity.Name; - var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); - var tokenTextExisting = await tokenHelper.MatchToken(userClaimsPrincipal, "RefreshToken", refreshAccessTokenRequest.RefreshToken, Guid.Empty); - if (!tokenTextExisting) - { - return StatusCode(401, new { message = "Invalid to retrieve token through refreshToken" }); // message may be omitted in prod build, to avoid exposing implementation details. - } + if (AuthenticationHeaderValue.TryParse(Request.Headers.Authorization, out var headerValue)){ + var scehma = headerValue.Scheme; + Debug.Assert("bearer".Equals(scehma, StringComparison.OrdinalIgnoreCase)); + var accessToken = headerValue.Parameter; + var jwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken); + var uniqueNameClaim = jwtSecurityToken.Claims.Single(d => d.Type == "unique_name"); + var username = uniqueNameClaim.Value; + var user = await UserManager.FindByNameAsync(username); - //return await tokenHelper.GenerateJwtToken(user, username, connectionId); //the old refresh token is removed + if (user == null) + { + return BadRequest(new { message = "Username or password is invalid" }); + } + + var tokenHelper = new UserTokenHelper(UserManager, symmetricSecurityKey, authSettings); + var tokenTextExisting = await tokenHelper.MatchToken(user, "RefreshToken", refreshAccessTokenRequest.refresh_token, Guid.Empty); + if (!tokenTextExisting) + { + return StatusCode(401, new { message = "Invalid to retrieve token through refreshToken" }); // message may be omitted in prod build, to avoid exposing implementation details. + } + + return await tokenHelper.GenerateJwtToken(user, username, Guid.Empty); + } } throw new NotSupportedException(); diff --git a/Core3WebApi/Controllers/HeroesController.cs b/Core3WebApi/Controllers/HeroesController.cs index 4491ddf..1958e03 100644 --- a/Core3WebApi/Controllers/HeroesController.cs +++ b/Core3WebApi/Controllers/HeroesController.cs @@ -77,8 +77,6 @@ public Hero PostWithQuery([FromQuery] string name)//.net core difference: requir [HttpPost] public async Task Post([FromBody] string name)//.net core difference: requires explicit decorattion { - ClaimsPrincipal userClaimsPrincipal = Request.HttpContext.User; - var user = await userManager.GetUserAsync(userClaimsPrincipal); var max = HeroesData.Instance.Dic.Keys.Max(); var hero = new Hero { Id = max + 1, Name = name }; _ = HeroesData.Instance.Dic.TryAdd(max + 1, hero); diff --git a/Core3WebApi/Controllers/PolymorphismController.cs b/Core3WebApi/Controllers/PolymorphismController.cs index df775b0..9acd161 100644 --- a/Core3WebApi/Controllers/PolymorphismController.cs +++ b/Core3WebApi/Controllers/PolymorphismController.cs @@ -15,25 +15,25 @@ public class PolymorphismController : ControllerBase [Consumes("application/x-www-form-urlencoded")] //need explicit declaration for sharing endpoint public async Task PostTokenRequestAsFormData([FromForm] RequestBase model) { - if (model.GrantType == "password" && model is ROPCRequst) + if (model.grant_type == "password" && model is ROPCRequst) { return new AccessTokenResponse { - TokenType = "bearer", - AccessToken = "AccessTokenString", - ExpiresIn = 100, - RefreshToken = "RefreshTokenString", + token_type = "bearer", + access_token = "AccessTokenString", + expires_in = 100, + refresh_token = "RefreshTokenString", Scope = "some scope" }; } - else if (model.GrantType == "refresh_token" && model is RefreshAccessTokenRequest) + else if (model.grant_type == "refresh_token" && model is RefreshAccessTokenRequest) { return new AccessTokenResponse { - TokenType = "bearer", - AccessToken = "NewAccessTokenString", - ExpiresIn = 100, - RefreshToken = "NewRefreshTokenString", + token_type = "bearer", + access_token = "NewAccessTokenString", + expires_in = 100, + refresh_token = "NewRefreshTokenString", Scope = "some scope" }; } diff --git a/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs b/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs index 88452fc..576bc97 100644 --- a/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs +++ b/Core3WebApi/Helpers/OAuth2RequestBinderProvider.cs @@ -79,7 +79,7 @@ public async Task BindModelAsync(ModelBindingContext bindingContext) if (newBindingContext.Result.IsModelSet) { - (newBindingContext.Result.Model as RequestBase).GrantType = modelTypeValue; + (newBindingContext.Result.Model as RequestBase).grant_type = modelTypeValue; // Setting the ValidationState ensures properties on derived types are correctly bindingContext.ValidationState[newBindingContext.Result.Model] = new ValidationStateEntry { diff --git a/Core3WebApi/Helpers/UserTokenHelper.cs b/Core3WebApi/Helpers/UserTokenHelper.cs index 060b53a..9d24066 100644 --- a/Core3WebApi/Helpers/UserTokenHelper.cs +++ b/Core3WebApi/Helpers/UserTokenHelper.cs @@ -68,16 +68,16 @@ public async Task MatchToken(ApplicationUser user, string purpose, string return tokenValue == storedToken; } - public async Task MatchToken(ClaimsPrincipal userClaimsPrincipal, string purpose, string tokenValue, Guid connectionId) - { - var user = await userManager.GetUserAsync(userClaimsPrincipal); - if (user==null){ - return false; - } - //var isValid = await userManager.VerifyUserTokenAsync(user, authSettings.TokenProviderName, "RefreshToken", tokenValue); probably no need to call this to avoid mix token purpose usages? - //and can not handle the expiry of refresh token, or any token needs to be expired. Also, cross machines issues as documented on https://stackoverflow.com/questions/51966010/identity-framework-generateusertoken-validation-issue - return await MatchToken(user, purpose, tokenValue, connectionId); - } + //public async Task MatchToken(ClaimsPrincipal userClaimsPrincipal, string purpose, string tokenValue, Guid connectionId) + //{ + // var user = await userManager.GetUserAsync(userClaimsPrincipal); + // if (user==null){ + // return false; + // } + // //var isValid = await userManager.VerifyUserTokenAsync(user, authSettings.TokenProviderName, "RefreshToken", tokenValue); probably no need to call this to avoid mix token purpose usages? + // //and can not handle the expiry of refresh token, or any token needs to be expired. Also, cross machines issues as documented on https://stackoverflow.com/questions/51966010/identity-framework-generateusertoken-validation-issue + // return await MatchToken(user, purpose, tokenValue, connectionId); + //} /// /// Generate token and refreshToken. @@ -111,12 +111,12 @@ public async Task> GenerateJwtToken(Application return new TokenResponseModel() { - AccessToken = accessToken, - TokenType = "Bearer", + access_token = accessToken, + token_type = "Bearer", Username = username, - ExpiresIn = Convert.ToInt32(span.TotalSeconds), + expires_in = Convert.ToInt32(span.TotalSeconds), Expires = expires.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), - RefreshToken = refreshToken, + refresh_token = refreshToken, ConnectionId = connectionId, }; //The token contains roles info as shown at https://jwt.io/ diff --git a/CoreWebApi.ClientApi/AuthClient.cs b/CoreWebApi.ClientApi/AuthClient.cs index 82060f2..a83ebe3 100644 --- a/CoreWebApi.ClientApi/AuthClient.cs +++ b/CoreWebApi.ClientApi/AuthClient.cs @@ -40,7 +40,7 @@ public AuthClient(System.Net.Http.HttpClient client, JsonSerializerOptions jsonS using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var pairs = new KeyValuePair[] { - new KeyValuePair( "grant_type", model.GrantType ), + new KeyValuePair( "grant_type", model.grant_type ), new KeyValuePair( "username", model.Username ), new KeyValuePair ( "password", model.Password ) }; @@ -65,8 +65,8 @@ public AuthClient(System.Net.Http.HttpClient client, JsonSerializerOptions jsonS using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, requestUri); var pairs = new KeyValuePair[] { - new KeyValuePair( "grant_type", model.GrantType ), - new KeyValuePair( "refresh_token", model.RefreshToken ), + new KeyValuePair( "grant_type", model.grant_type ), + new KeyValuePair( "refresh_token", model.refresh_token ), new KeyValuePair ( "scope", model.Scope ) }; var content = new FormUrlEncodedContent(pairs); diff --git a/CoreWebApi.ClientApi/WebApiClientAuto.cs b/CoreWebApi.ClientApi/WebApiClientAuto.cs index a573afe..7555624 100644 --- a/CoreWebApi.ClientApi/WebApiClientAuto.cs +++ b/CoreWebApi.ClientApi/WebApiClientAuto.cs @@ -7810,16 +7810,16 @@ public class AccessTokenResponse : Fonlow.Auth.Models.Client.TokenResponseBase [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="access_token")] [System.Text.Json.Serialization.JsonPropertyName("access_token")] - public string AccessToken { get; set; } + public string access_token { get; set; } [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="expires_in")] [System.Text.Json.Serialization.JsonPropertyName("expires_in")] - public int ExpiresIn { get; set; } + public int expires_in { get; set; } [System.Runtime.Serialization.DataMember(Name="refresh_token")] [System.Text.Json.Serialization.JsonPropertyName("refresh_token")] - public string RefreshToken { get; set; } + public string refresh_token { get; set; } [System.Runtime.Serialization.DataMember()] public string Scope { get; set; } @@ -7832,7 +7832,7 @@ public class RefreshAccessTokenRequest : Fonlow.Auth.Models.Client.RequestBase [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="refresh_token")] [System.Text.Json.Serialization.JsonPropertyName("refresh_token")] - public string RefreshToken { get; set; } + public string refresh_token { get; set; } [System.Runtime.Serialization.DataMember()] public string Scope { get; set; } @@ -7845,7 +7845,7 @@ public class RequestBase : object [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="grant_type")] [System.Text.Json.Serialization.JsonPropertyName("grant_type")] - public string GrantType { get; set; } + public string grant_type { get; set; } } [System.Runtime.Serialization.DataContract(Namespace="http://demoapp.client/2024")] @@ -7871,7 +7871,7 @@ public class TokenResponseBase : object [System.ComponentModel.DataAnnotations.Required()] [System.Runtime.Serialization.DataMember(Name="token_type")] [System.Text.Json.Serialization.JsonPropertyName("token_type")] - public string TokenType { get; set; } + public string token_type { get; set; } } } namespace Fonlow.WebApp.Accounts.Client diff --git a/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs b/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs index f21cc08..0090824 100644 --- a/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs +++ b/Fonlow.AspNetCore.Identity/ApplicationUserManager.cs @@ -24,12 +24,5 @@ public Task FindByIdAsync(Guid userId) { return base.FindByIdAsync(userId.ToString()); } - - //public override Task GetUserAsync(ClaimsPrincipal principal) - //{ - // ArgumentNullException.ThrowIfNull(principal); - // var id = GetUserId(principal); - // return id == null ? Task.FromResult(null) : FindByIdAsync(id); - //} } } \ No newline at end of file diff --git a/Fonlow.WebApp.Accounts/Models.cs b/Fonlow.WebApp.Accounts/Models.cs index f27b556..18cb51c 100644 --- a/Fonlow.WebApp.Accounts/Models.cs +++ b/Fonlow.WebApp.Accounts/Models.cs @@ -15,7 +15,7 @@ public class RequestBase [JsonPropertyName("grant_type")] [JsonPropertyOrder(-10)] [DataMember(Name = "grant_type")] - public string GrantType { get; set; } + public string grant_type { get; set; } } /// @@ -48,7 +48,7 @@ public class RefreshAccessTokenRequest : RequestBase [Required] [JsonPropertyName("refresh_token")] [DataMember(Name = "refresh_token")] - public string RefreshToken { get; set; } + public string refresh_token { get; set; } [DataMember] public string Scope { get; set; } @@ -64,7 +64,7 @@ public abstract class TokenResponseBase [JsonPropertyOrder(-10)] [JsonPropertyName("token_type")] [DataMember(Name = "token_type")] - public string TokenType { get; set; } + public string token_type { get; set; } } /// @@ -76,7 +76,7 @@ public class AccessTokenResponse : TokenResponseBase [JsonPropertyName("access_token")] [DataMember(Name = "access_token")] [Required] - public string AccessToken { get; set; } + public string access_token { get; set; } /// /// In the spec, it is recommended, however, it is bad in practice if not required. @@ -84,11 +84,11 @@ public class AccessTokenResponse : TokenResponseBase [JsonPropertyName("expires_in")] [DataMember(Name = "expires_in")] [Required] - public int ExpiresIn { get; set; } + public int expires_in { get; set; } [JsonPropertyName("refresh_token")] [DataMember(Name = "refresh_token")] - public string RefreshToken { get; set; } + public string refresh_token { get; set; } [DataMember] public string Scope { get; set; } diff --git a/Tests/AuthRemoteTests/AccountFacts.cs b/Tests/AuthRemoteTests/AccountFacts.cs index 0ce3bea..8a0988f 100644 --- a/Tests/AuthRemoteTests/AccountFacts.cs +++ b/Tests/AuthRemoteTests/AccountFacts.cs @@ -46,7 +46,7 @@ public void TestRemovedUserTryToLoginThrows() Assert.Equal(newUsername, newUserTokenModel.Username); using var userHttpClient = new HttpClient(); userHttpClient.BaseAddress = baseUri; - userHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(newUserTokenModel.TokenType, newUserTokenModel.AccessToken); + userHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(newUserTokenModel.token_type, newUserTokenModel.access_token); var heroesApi = new Heroes(userHttpClient); heroesApi.GetHeros(); @@ -55,10 +55,10 @@ public void TestRemovedUserTryToLoginThrows() var tokenText = GetTokenWithNewClient(baseUri, "admin", "Pppppp*8"); Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); var userId = accountApi.GetUserIdByUser(newUsername); accountApi.RemoveUser(userId); @@ -67,11 +67,11 @@ public void TestRemovedUserTryToLoginThrows() Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); // User refresh token to gain access without login should fail - Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newUserTokenModel.RefreshToken, newUserTokenModel.Username, newUserTokenModel.ConnectionId)); + Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newUserTokenModel.refresh_token, newUserTokenModel.Username, newUserTokenModel.ConnectionId)); heroesApi.GetHeros(); // the access token is still working, for a while. System.Threading.Thread.Sleep(307100); - Assert.Throws(() => TestAuthorizedConnection(newUserTokenModel.TokenType, newUserTokenModel.AccessToken)); // new connection should fail + Assert.Throws(() => TestAuthorizedConnection(newUserTokenModel.token_type, newUserTokenModel.access_token)); // new connection should fail for (int i = 0; i < 10; i++) { heroesApi.GetHeros(); // existing connection is still working, as long as the HTTP connection remains. @@ -101,7 +101,7 @@ HttpClient CreateAdminHttpClient(){ var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); return httpClient; } @@ -130,11 +130,11 @@ public void TestRegisterWithInvalidUsernameThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); var stamp = DateTime.Now.ToString("yyMMddHHmmssfff"); var newUsername = "John " + stamp; // a space make the username invalid diff --git a/Tests/AuthRemoteTests/TokenFacts.cs b/Tests/AuthRemoteTests/TokenFacts.cs index decd601..9303521 100644 --- a/Tests/AuthRemoteTests/TokenFacts.cs +++ b/Tests/AuthRemoteTests/TokenFacts.cs @@ -53,7 +53,7 @@ public void Test100SiginWithNewHttpClient() Assert.NotEmpty(tokenText); var toeknModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(toeknModel.AccessToken); + Assert.NotNull(toeknModel.access_token); } } @@ -64,26 +64,26 @@ public void Test100RefreshTokenWithNewHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var currentRefreshToken = tokenModel.RefreshToken; - var currentAccesstoken = tokenModel.AccessToken; - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + var currentRefreshToken = tokenModel.refresh_token; + var currentAccesstoken = tokenModel.access_token; + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); for (int i = 0; i < 100; i++) { var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, currentRefreshToken, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(currentRefreshToken, newTokenModel.RefreshToken); + Assert.NotEqual(currentRefreshToken, newTokenModel.refresh_token); //Assert.NotEqual(currentAccesstoken, newTokenModel.AccessToken); sometimes equal, probably due to that I request frequently. - currentRefreshToken = newTokenModel.RefreshToken; - currentAccesstoken = newTokenModel.AccessToken; // for bearer token in new request + currentRefreshToken = newTokenModel.refresh_token; + currentAccesstoken = newTokenModel.access_token; // for bearer token in new request } //Assert.NotEqual(tokenModel.AccessToken, currentAccesstoken); sometime equal - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. } [Fact] @@ -93,11 +93,11 @@ public void TestRefreshTokenWithNewHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - TestAuthorizedNewConnection(newTokenModel.TokenType, newTokenModel.AccessToken); + TestAuthorizedNewConnection(newTokenModel.token_type, newTokenModel.access_token); } /// @@ -111,14 +111,14 @@ public void TestAccessTokenExpiry() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); - output.WriteLine($"token ExpiresIn {tokenModel.ExpiresIn}; Expires: {tokenModel.Expires}"); + Assert.NotNull(tokenModel.refresh_token); + output.WriteLine($"token ExpiresIn {tokenModel.expires_in}; Expires: {tokenModel.Expires}"); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); Thread.Sleep(5050); // expiry is 5 seconds in appsetings.json of the Web service. - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // should work because of the 2-seconds clock skew. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // should work because of the 2-seconds clock skew. Thread.Sleep(clockSkewSeconds); - var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken)); + var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); } @@ -148,21 +148,21 @@ public void TestAccessTokenExpiryThenGetNewViaRefreshToken() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); - output.WriteLine($"token ExpiresIn {tokenModel.ExpiresIn}; Expires: {tokenModel.Expires}"); + Assert.NotNull(tokenModel.refresh_token); + output.WriteLine($"token ExpiresIn {tokenModel.expires_in}; Expires: {tokenModel.Expires}"); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); Thread.Sleep(5000); Thread.Sleep(clockSkewSeconds); - var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken)); + var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - Assert.NotEqual(tokenModel.AccessToken, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.access_token, newTokenModel.access_token); } /// @@ -175,9 +175,9 @@ public void TestRefreshTokenWithCorruptedDataThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken + "A", tokenModel.Username, tokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token + "A", tokenModel.Username, tokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); Assert.Contains("Invalid to retrieve token through refreshToken", ex.Response); output.WriteLine("throws"); @@ -193,9 +193,9 @@ public void TestRefreshTokenWithInvalidConnectionIdDataThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, Guid.NewGuid())); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, Guid.NewGuid())); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); Assert.Contains("Invalid to retrieve token through refreshToken", ex.Response); } @@ -209,7 +209,7 @@ public void Test100SiginWithSameHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.AccessToken); + Assert.NotNull(tokenModel.access_token); } } @@ -220,26 +220,26 @@ public void Test100RefreshTokenWithSameHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var currentRefreshToken = tokenModel.RefreshToken; - var currentAccesstoken = tokenModel.AccessToken; - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + var currentRefreshToken = tokenModel.refresh_token; + var currentAccesstoken = tokenModel.access_token; + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); for (int i = 0; i < 100; i++) { var newTokenModel = GetTokenResponseModelByRefreshTokenWithSameClient(baseUri, currentRefreshToken, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(currentRefreshToken, newTokenModel.RefreshToken); + Assert.NotEqual(currentRefreshToken, newTokenModel.refresh_token); //Assert.NotEqual(currentAccesstoken, newTokenModel.AccessToken); sometimes equal, probably due to that I request frequently. - currentRefreshToken = newTokenModel.RefreshToken; - currentAccesstoken = newTokenModel.AccessToken; // for bearer token in new request + currentRefreshToken = newTokenModel.refresh_token; + currentAccesstoken = newTokenModel.access_token; // for bearer token in new request } //Assert.NotEqual(tokenModel.AccessToken, currentAccesstoken); //sometimes still equal - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. } /// @@ -252,17 +252,17 @@ public void TestLogoutThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.Logout(tokenModel.ConnectionId); // this will remove the refresh token of the user on connnectionId - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // still working, because JWT is stateless. This is a normal behavior. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // still working, because JWT is stateless. This is a normal behavior. } /// @@ -275,20 +275,20 @@ public void TestRemoveOldUserTokensThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId); + GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, newTokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, newTokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.RemoveOldUserTokens(DateTime.UtcNow); // Remove all user tokens, typically refresh tokens - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); } @@ -299,20 +299,20 @@ public void TestAdminRemoveUserTokensThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId); + GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, newTokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, newTokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.AdminRemoverRefreshTokensOfUsers(newTokenModel.Username); - Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId)); + Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId)); } HttpClient CreateAdminHttpClient() @@ -321,7 +321,7 @@ HttpClient CreateAdminHttpClient() var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); return httpClient; } diff --git a/Tests/AuthTests/AccountFacts.cs b/Tests/AuthTests/AccountFacts.cs index 784d714..6ee7ea3 100644 --- a/Tests/AuthTests/AccountFacts.cs +++ b/Tests/AuthTests/AccountFacts.cs @@ -55,7 +55,7 @@ public void TestRemovedUserTryToLoginThrows() Assert.Equal(newUsername, newUserTokenModel.Username); using var userHttpClient = new HttpClient(); userHttpClient.BaseAddress = baseUri; - userHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(newUserTokenModel.TokenType, newUserTokenModel.AccessToken); + userHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(newUserTokenModel.token_type, newUserTokenModel.access_token); var heroesApi = new Heroes(userHttpClient); heroesApi.GetHeros(); @@ -64,10 +64,10 @@ public void TestRemovedUserTryToLoginThrows() var tokenText = GetTokenWithNewClient(baseUri, "admin", "Pppppp*8"); Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); var userId = accountApi.GetUserIdByUser(newUsername); accountApi.RemoveUser(userId); @@ -76,11 +76,11 @@ public void TestRemovedUserTryToLoginThrows() Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); // User refresh token to gain access without login should fail - Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newUserTokenModel.RefreshToken, newUserTokenModel.Username, newUserTokenModel.ConnectionId)); + Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newUserTokenModel.refresh_token, newUserTokenModel.Username, newUserTokenModel.ConnectionId)); heroesApi.GetHeros(); // the access token is still working, for a while. System.Threading.Thread.Sleep(7100); - Assert.Throws(() => TestAuthorizedConnection(newUserTokenModel.TokenType, newUserTokenModel.AccessToken)); // new connection should fail + Assert.Throws(() => TestAuthorizedConnection(newUserTokenModel.token_type, newUserTokenModel.access_token)); // new connection should fail for (int i = 0; i < 10; i++) { heroesApi.GetHeros(); // existing connection is still working, as long as the HTTP connection remains. @@ -110,7 +110,7 @@ HttpClient CreateAdminHttpClient(){ var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); return httpClient; } @@ -139,11 +139,11 @@ public void TestRegisterWithInvalidUsernameThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); var stamp = DateTime.Now.ToString("yyMMddHHmmssfff"); var newUsername = "John " + stamp; // a space make the username invalid diff --git a/Tests/AuthTests/AuthFacts.cs b/Tests/AuthTests/AuthFacts.cs index 759d7fc..6cf6f58 100644 --- a/Tests/AuthTests/AuthFacts.cs +++ b/Tests/AuthTests/AuthFacts.cs @@ -55,16 +55,16 @@ public async Task TestPostRopcTokenRequestAsFormDataToAuthAsync() { var r = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst { - GrantType = "password", + grant_type = "password", Username = "admin", Password = "Pppppp*8" }); - Assert.Equal("bearer", r.TokenType, true); - Assert.NotNull(r.AccessToken); - Assert.NotNull(r.RefreshToken); + Assert.Equal("bearer", r.token_type, true); + Assert.NotNull(r.access_token); + Assert.NotNull(r.refresh_token); //Assert.Equal("some scope", r.Scope); - Assert.True(r.ExpiresIn > 0); + Assert.True(r.expires_in > 0); } [Fact] @@ -72,26 +72,26 @@ public async Task TestPostRefreshTokenRequestAsFormDataToAuthAsync() { var ra = await api.PostRopcTokenRequestAsFormDataToAuthAsync(new ROPCRequst { - GrantType = "password", + grant_type = "password", Username = "admin", Password = "Pppppp*8" }); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); - client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ra.AccessToken); + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ra.access_token); AuthClient authClient = new AuthClient(client); var r = await authClient.PostRefreshTokenRequestAsFormDataToAuthAsync(new RefreshAccessTokenRequest { - GrantType = "refresh_token", - RefreshToken = "RefreshTokenString" + grant_type = "refresh_token", + refresh_token = ra.refresh_token }); - Assert.Equal("bearer", r.TokenType, true); - Assert.NotNull(r.AccessToken); - Assert.NotNull(r.RefreshToken); + Assert.Equal("bearer", r.token_type, true); + Assert.NotNull(r.access_token); + Assert.NotNull(r.refresh_token); //Assert.Equal("some scope", r.Scope); - Assert.True(r.ExpiresIn > 0); + Assert.True(r.expires_in > 0); } } } diff --git a/Tests/AuthTests/TokenFacts.cs b/Tests/AuthTests/TokenFacts.cs index 23724df..630b9ba 100644 --- a/Tests/AuthTests/TokenFacts.cs +++ b/Tests/AuthTests/TokenFacts.cs @@ -55,7 +55,7 @@ public void TestAccessTokenOnce() Assert.NotEmpty(tokenText); var toeknModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(toeknModel.AccessToken); + Assert.NotNull(toeknModel.access_token); } [Fact] @@ -67,7 +67,7 @@ public void Test100SiginWithNewHttpClient() Assert.NotEmpty(tokenText); var toeknModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(toeknModel.AccessToken); + Assert.NotNull(toeknModel.access_token); } } @@ -78,26 +78,26 @@ public void Test100RefreshTokenWithNewHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var currentRefreshToken = tokenModel.RefreshToken; - var currentAccesstoken = tokenModel.AccessToken; - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + var currentRefreshToken = tokenModel.refresh_token; + var currentAccesstoken = tokenModel.access_token; + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); for (int i = 0; i < 100; i++) { var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, currentRefreshToken, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(currentRefreshToken, newTokenModel.RefreshToken); - //Assert.NotEqual(currentAccesstoken, newTokenModel.AccessToken); sometimes equal, probably due to that I request frequently. - currentRefreshToken = newTokenModel.RefreshToken; - currentAccesstoken = newTokenModel.AccessToken; // for bearer token in new request + Assert.NotEqual(currentRefreshToken, newTokenModel.refresh_token); + //Assert.NotEqual(currentAccesstoken, newTokenModel.access_token); sometimes equal, probably due to that I request frequently. + currentRefreshToken = newTokenModel.refresh_token; + currentAccesstoken = newTokenModel.access_token; // for bearer token in new request } - //Assert.NotEqual(tokenModel.AccessToken, currentAccesstoken); sometime equal - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + //Assert.NotEqual(tokenModel.access_token, currentAccesstoken); sometime equal + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. } [Fact] @@ -107,11 +107,11 @@ public void TestRefreshTokenWithNewHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - TestAuthorizedNewConnection(newTokenModel.TokenType, newTokenModel.AccessToken); + TestAuthorizedNewConnection(newTokenModel.token_type, newTokenModel.access_token); } /// @@ -129,14 +129,14 @@ public void TestAccessTokenExpiry() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); - output.WriteLine($"token ExpiresIn {tokenModel.ExpiresIn}; Expires: {tokenModel.Expires}"); + Assert.NotNull(tokenModel.refresh_token); + output.WriteLine($"token expires_in {tokenModel.expires_in}; Expires: {tokenModel.Expires}"); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); Thread.Sleep(5050); // expiry is 5 seconds in appsetings.json of the Web service. - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // should work because of the 2-seconds clock skew. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // should work because of the 2-seconds clock skew. Thread.Sleep(clockSkewSeconds); - var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken)); + var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); } @@ -170,20 +170,20 @@ public void TestAccessTokenExpiryThenGetNewViaRefreshToken() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); - output.WriteLine($"token ExpiresIn {tokenModel.ExpiresIn}; Expires: {tokenModel.Expires}"); + Assert.NotNull(tokenModel.refresh_token); + output.WriteLine($"token expires_in {tokenModel.expires_in}; Expires: {tokenModel.Expires}"); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); Thread.Sleep(7050); - var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken)); + var ex = Assert.Throws(() => TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - Assert.NotEqual(tokenModel.AccessToken, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.access_token, newTokenModel.access_token); } /// @@ -196,9 +196,9 @@ public void TestRefreshTokenWithCorruptedDataThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken + "A", tokenModel.Username, tokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token + "A", tokenModel.Username, tokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); Assert.Contains("Invalid to retrieve token through refreshToken", ex.Response); output.WriteLine("throws"); @@ -214,9 +214,9 @@ public void TestRefreshTokenWithInvalidConnectionIdDataThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, Guid.NewGuid())); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, Guid.NewGuid())); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); Assert.Contains("Invalid to retrieve token through refreshToken", ex.Response); } @@ -230,7 +230,7 @@ public void Test100SiginWithSameHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.AccessToken); + Assert.NotNull(tokenModel.access_token); } } @@ -241,26 +241,26 @@ public void Test100RefreshTokenWithSameHttpClient() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var currentRefreshToken = tokenModel.RefreshToken; - var currentAccesstoken = tokenModel.AccessToken; - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + var currentRefreshToken = tokenModel.refresh_token; + var currentAccesstoken = tokenModel.access_token; + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); for (int i = 0; i < 100; i++) { var newTokenModel = GetTokenResponseModelByRefreshTokenWithSameClient(baseUri, currentRefreshToken, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(currentRefreshToken, newTokenModel.RefreshToken); - //Assert.NotEqual(currentAccesstoken, newTokenModel.AccessToken); sometimes equal, probably due to that I request frequently. - currentRefreshToken = newTokenModel.RefreshToken; - currentAccesstoken = newTokenModel.AccessToken; // for bearer token in new request + Assert.NotEqual(currentRefreshToken, newTokenModel.refresh_token); + //Assert.NotEqual(currentAccesstoken, newTokenModel.access_token); sometimes equal, probably due to that I request frequently. + currentRefreshToken = newTokenModel.refresh_token; + currentAccesstoken = newTokenModel.access_token; // for bearer token in new request } - //Assert.NotEqual(tokenModel.AccessToken, currentAccesstoken); //sometimes still equal - TestAuthorizedNewConnection(tokenModel.TokenType, currentAccesstoken); + //Assert.NotEqual(tokenModel.access_token, currentAccesstoken); //sometimes still equal + TestAuthorizedNewConnection(tokenModel.token_type, currentAccesstoken); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // old token is till working. To revoke, refer to https://stackoverflow.com/questions/62874537/jwt-token-forcefully-expire-in-asp-net-core-3-1, as JWT is by design not revokeable, and ASP.NET (Core) security hornor this. Another way simplier, just to set the expiry with 5 minutes span, if 5 minutes is accetable by your enterprise security policy. } /// @@ -273,17 +273,17 @@ public void TestLogoutThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.Logout(tokenModel.ConnectionId); // this will remove the refresh token of the user on connnectionId - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); - TestAuthorizedNewConnection(tokenModel.TokenType, tokenModel.AccessToken); // still working, because JWT is stateless. This is a normal behavior. + TestAuthorizedNewConnection(tokenModel.token_type, tokenModel.access_token); // still working, because JWT is stateless. This is a normal behavior. } /// @@ -296,20 +296,20 @@ public void TestRemoveOldUserTokensThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId); + GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, newTokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, newTokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.RemoveOldUserTokens(DateTime.UtcNow); // Remove all user tokens, typically refresh tokens - var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId)); + var ex = Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId)); Assert.Equal(System.Net.HttpStatusCode.Unauthorized, ex.StatusCode); } @@ -320,20 +320,20 @@ public void TestAdminRemoveUserTokensThenRefreshTokenThrows() Assert.NotEmpty(tokenText); var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); - Assert.NotNull(tokenModel.RefreshToken); + Assert.NotNull(tokenModel.refresh_token); - var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.RefreshToken, tokenModel.Username, tokenModel.ConnectionId); + var newTokenModel = GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, tokenModel.refresh_token, tokenModel.Username, tokenModel.ConnectionId); Assert.Equal(tokenModel.Username, newTokenModel.Username); - Assert.NotEqual(tokenModel.RefreshToken, newTokenModel.RefreshToken); - TestAuthorizedNewConnection(tokenModel.TokenType, newTokenModel.AccessToken); + Assert.NotEqual(tokenModel.refresh_token, newTokenModel.refresh_token); + TestAuthorizedNewConnection(tokenModel.token_type, newTokenModel.access_token); - GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId); + GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId); using var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, newTokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, newTokenModel.access_token); var accountApi = new DemoWebApi.Controllers.Client.Account(httpClient); accountApi.AdminRemoverRefreshTokensOfUsers(newTokenModel.Username); - Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.RefreshToken, newTokenModel.Username, newTokenModel.ConnectionId)); + Assert.Throws(() => GetTokenResponseModelByRefreshTokenWithNewClient(baseUri, newTokenModel.refresh_token, newTokenModel.Username, newTokenModel.ConnectionId)); } HttpClient CreateAdminHttpClient() @@ -342,7 +342,7 @@ HttpClient CreateAdminHttpClient() var tokenModel = System.Text.Json.JsonSerializer.Deserialize(tokenText); var httpClient = new HttpClient(); httpClient.BaseAddress = baseUri; - httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.TokenType, tokenModel.AccessToken); + httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(tokenModel.token_type, tokenModel.access_token); return httpClient; } diff --git a/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs b/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs deleted file mode 100644 index 648553f..0000000 --- a/Tests/ModelsUnitTests/AuthModelsConvertersTests.cs +++ /dev/null @@ -1,76 +0,0 @@ -using Fonlow.Auth.Models; -using Fonlow.Text.Json.Auth; -using System.Text.Json; - -namespace ConvertersTests -{ - public class AuthModelsConvertersTests - { - [Fact] - public void TestROPCRequstSerialize() - { - ROPCRequst r = new ROPCRequst - { - GrantType = "password", - Username = "Somebody", - Password = "mypwd" - }; - - var s = System.Text.Json.JsonSerializer.Serialize(r, new JsonSerializerOptions(JsonSerializerDefaults.Web)); - Assert.Equal("{\"grant_type\":\"password\",\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null}", s); - } - - - [Fact] - public void TestROPCRequstDeserialize() - { - var s = "{\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null,\"grant_type\":\"password\"}"; - var r = System.Text.Json.JsonSerializer.Deserialize(s, new JsonSerializerOptions(JsonSerializerDefaults.Web)); - Assert.Equal("password", r.GrantType); - Assert.Equal("Somebody", r.Username); - } - - [Fact] - public void TestROPCRequstDeserializeAsRequestBase() - { - var s = "{\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":null,\"grant_type\":\"password\"}"; - var r = System.Text.Json.JsonSerializer.Deserialize(s, new JsonSerializerOptions(JsonSerializerDefaults.Web)); - Assert.Equal("password", r.GrantType); - Assert.Null(r as ROPCRequst); - } - - [Fact] - public void TestROPCRequstDeserializeAsRequestBaseWithConverter() - { - var options = new System.Text.Json.JsonSerializerOptions(new JsonSerializerOptions(JsonSerializerDefaults.Web)); - options.Converters.Add(new TokenRequestConverter()); - var s = "{\"grant_type\":\"password\",\"username\":\"Somebody\",\"password\":\"mypwd\",\"scope\":\"Something somewhere\"}"; - var r = System.Text.Json.JsonSerializer.Deserialize(s, options); - Assert.Equal("password", r.GrantType); - Assert.Equal("Somebody", (r as ROPCRequst).Username); - Assert.Equal("mypwd", (r as ROPCRequst).Password); - Assert.Equal("Something somewhere", (r as ROPCRequst).Scope); - } - - [Fact] - public void TestRefreshTokenRequstDeserializeAsRequestBaseWithConverter() - { - var options = new System.Text.Json.JsonSerializerOptions(new JsonSerializerOptions(JsonSerializerDefaults.Web)); - options.Converters.Add(new TokenRequestConverter()); - var request = new RefreshAccessTokenRequest - { - GrantType = "refresh_token", - RefreshToken = "LongTokenString", - Scope = "Something", - }; - - var s = JsonSerializer.Serialize(request, options); - var r = System.Text.Json.JsonSerializer.Deserialize(s, options); - Assert.Equal("refresh_token", r.GrantType); - Assert.Equal("LongTokenString", (r as RefreshAccessTokenRequest).RefreshToken); - Assert.Equal("Something", (r as RefreshAccessTokenRequest).Scope); - } - - - } -} diff --git a/Tests/ModelsUnitTests/ModelsUnitTests.csproj b/Tests/ModelsUnitTests/ModelsUnitTests.csproj deleted file mode 100644 index 29d497e..0000000 --- a/Tests/ModelsUnitTests/ModelsUnitTests.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net8.0 - enable - - false - true - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - -