├── .editorconfig ├── .github └── workflows │ ├── build.yml │ └── publish.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── Ardalis.ApiClient.sln ├── LICENSE ├── README.md ├── src └── Ardalis.ApiClient │ ├── Ardalis.ApiClient.csproj │ ├── BaseApiCaller.cs │ ├── BaseAsyncApiCaller.cs │ ├── DictionaryExtensions.cs │ ├── HttpResponse.cs │ ├── HttpResponseGeneric.cs │ ├── HttpService.cs │ ├── IBaseApiCaller.cs │ ├── License.txt │ ├── StringExtensions.cs │ ├── TimeoutType.cs │ └── icon.png └── tests └── Ardalis.ApiClient.UnitTests ├── Ardalis.ApiClient.UnitTests.csproj └── DictionaryAddIfNotNull.cs /.editorconfig: -------------------------------------------------------------------------------- 1 | # To learn more about .editorconfig see https://aka.ms/editorconfigdocs 2 | ############################### 3 | # Core EditorConfig Options # 4 | ############################### 5 | # All files 6 | [*] 7 | indent_style = space 8 | # Code files 9 | [*.{cs,csx,vb,vbx}] 10 | indent_size = 2 11 | insert_final_newline = true 12 | charset = utf-8-bom 13 | ############################### 14 | # .NET Coding Conventions # 15 | ############################### 16 | [*.{cs,vb}] 17 | # Organize usings 18 | dotnet_sort_system_directives_first = true 19 | # this. preferences 20 | dotnet_style_qualification_for_field = false:silent 21 | dotnet_style_qualification_for_property = false:silent 22 | dotnet_style_qualification_for_method = false:silent 23 | dotnet_style_qualification_for_event = false:silent 24 | # Language keywords vs BCL types preferences 25 | dotnet_style_predefined_type_for_locals_parameters_members = true:silent 26 | dotnet_style_predefined_type_for_member_access = true:silent 27 | # Parentheses preferences 28 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent 29 | dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent 30 | dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent 31 | dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent 32 | # Modifier preferences 33 | dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent 34 | dotnet_style_readonly_field = true:suggestion 35 | # Expression-level preferences 36 | dotnet_style_object_initializer = true:suggestion 37 | dotnet_style_collection_initializer = true:suggestion 38 | dotnet_style_explicit_tuple_names = true:suggestion 39 | dotnet_style_null_propagation = true:suggestion 40 | dotnet_style_coalesce_expression = true:suggestion 41 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true:silent 42 | dotnet_style_prefer_inferred_tuple_names = true:suggestion 43 | dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion 44 | dotnet_style_prefer_auto_properties = true:silent 45 | dotnet_style_prefer_conditional_expression_over_assignment = true:silent 46 | dotnet_style_prefer_conditional_expression_over_return = true:silent 47 | ############################### 48 | # Naming Conventions # 49 | ############################### 50 | # Style Definitions 51 | dotnet_naming_style.pascal_case_style.capitalization = pascal_case 52 | # Use PascalCase for constant fields 53 | dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion 54 | dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields 55 | dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style 56 | dotnet_naming_symbols.constant_fields.applicable_kinds = field 57 | dotnet_naming_symbols.constant_fields.applicable_accessibilities = * 58 | dotnet_naming_symbols.constant_fields.required_modifiers = const 59 | # Instance fields are camelCase and start with _ 60 | dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion 61 | dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields 62 | dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style 63 | 64 | dotnet_naming_symbols.instance_fields.applicable_kinds = field 65 | 66 | dotnet_naming_style.instance_field_style.capitalization = camel_case 67 | dotnet_naming_style.instance_field_style.required_prefix = _ 68 | ############################### 69 | # C# Coding Conventions # 70 | ############################### 71 | [*.cs] 72 | # var preferences 73 | csharp_style_var_for_built_in_types = true:silent 74 | csharp_style_var_when_type_is_apparent = true:silent 75 | csharp_style_var_elsewhere = true:silent 76 | # Expression-bodied members 77 | csharp_style_expression_bodied_methods = false:silent 78 | csharp_style_expression_bodied_constructors = false:silent 79 | csharp_style_expression_bodied_operators = false:silent 80 | csharp_style_expression_bodied_properties = true:silent 81 | csharp_style_expression_bodied_indexers = true:silent 82 | csharp_style_expression_bodied_accessors = true:silent 83 | # Pattern matching preferences 84 | csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion 85 | csharp_style_pattern_matching_over_as_with_null_check = true:suggestion 86 | # Null-checking preferences 87 | csharp_style_throw_expression = true:suggestion 88 | csharp_style_conditional_delegate_call = true:suggestion 89 | # Modifier preferences 90 | csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion 91 | # Expression-level preferences 92 | csharp_prefer_braces = true:silent 93 | csharp_style_deconstructed_variable_declaration = true:suggestion 94 | csharp_prefer_simple_default_expression = true:suggestion 95 | csharp_style_pattern_local_over_anonymous_function = true:suggestion 96 | csharp_style_inlined_variable_declaration = true:suggestion 97 | ############################### 98 | # C# Formatting Rules # 99 | ############################### 100 | # New line preferences 101 | csharp_new_line_before_open_brace = all 102 | csharp_new_line_before_else = true 103 | csharp_new_line_before_catch = true 104 | csharp_new_line_before_finally = true 105 | csharp_new_line_before_members_in_object_initializers = true 106 | csharp_new_line_before_members_in_anonymous_types = true 107 | csharp_new_line_between_query_expression_clauses = true 108 | # Indentation preferences 109 | csharp_indent_case_contents = true 110 | csharp_indent_switch_labels = true 111 | csharp_indent_labels = flush_left 112 | # Space preferences 113 | csharp_space_after_cast = false 114 | csharp_space_after_keywords_in_control_flow_statements = true 115 | csharp_space_between_method_call_parameter_list_parentheses = false 116 | csharp_space_between_method_declaration_parameter_list_parentheses = false 117 | csharp_space_between_parentheses = false 118 | csharp_space_before_colon_in_inheritance_clause = true 119 | csharp_space_after_colon_in_inheritance_clause = true 120 | csharp_space_around_binary_operators = before_and_after 121 | csharp_space_between_method_declaration_empty_parameter_list_parentheses = false 122 | csharp_space_between_method_call_name_and_opening_parenthesis = false 123 | csharp_space_between_method_call_empty_parameter_list_parentheses = false 124 | # Wrapping preferences 125 | csharp_preserve_single_line_statements = true 126 | csharp_preserve_single_line_blocks = true 127 | ############################### 128 | # VB Coding Conventions # 129 | ############################### 130 | [*.vb] 131 | # Modifier preferences 132 | visual_basic_preferred_modifier_order = Partial,Default,Private,Protected,Public,Friend,NotOverridable,Overridable,MustOverride,Overloads,Overrides,MustInherit,NotInheritable,Static,Shared,Shadows,ReadOnly,WriteOnly,Dim,Const,WithEvents,Widening,Narrowing,Custom,Async:suggestion 133 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | on: 3 | workflow_dispatch: 4 | branches: [ main ] 5 | push: 6 | branches: [ main ] 7 | pull_request: 8 | branches: [ main ] 9 | 10 | jobs: 11 | build: 12 | 13 | runs-on: windows-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Setup .NET Core 18 | uses: actions/setup-dotnet@v1 19 | with: 20 | dotnet-version: 5.0.302 21 | - name: Install dependencies 22 | run: dotnet restore 23 | - name: Build 24 | run: dotnet build --configuration Release --no-restore 25 | - name: Test 26 | run: dotnet test --no-restore --verbosity normal 27 | 28 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: publish Ardalis.ApiClient to nuget 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main # Your default release branch 7 | paths: 8 | - 'src/Ardalis.ApiClient/**' 9 | jobs: 10 | publish: 11 | name: list on nuget 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2.3.4 15 | 16 | # Required for a specific dotnet version that doesn't come with ubuntu-latest / windows-latest 17 | # Visit bit.ly/2synnZl to see the list of SDKs that are pre-installed with ubuntu-latest / windows-latest 18 | - name: Setup dotnet 19 | uses: actions/setup-dotnet@v1 20 | with: 21 | dotnet-version: 5.0.202 22 | 23 | # Publish 24 | - name: publish on version change 25 | uses: rohith/publish-nuget@v2 26 | with: 27 | PROJECT_FILE_PATH: src/Ardalis.ApiClient/Ardalis.ApiClient.csproj # Relative to repository root 28 | # VERSION_FILE_PATH: Directory.Build.props # Filepath with version info, relative to repository root. Defaults to project file 29 | VERSION_REGEX: (.*)<\/Version> # Regex pattern to extract version info in a capturing group 30 | TAG_COMMIT: true # Flag to enable / disable git tagging 31 | TAG_FORMAT: v* # Format of the git tag, [*] gets replaced with version 32 | NUGET_KEY: ${{secrets.NUGET_API_KEY}} # nuget.org API key 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/tests/Ardalis.ApiClient.UnitTests/bin/Debug/net5.0/Ardalis.ApiClient.UnitTests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/tests/Ardalis.ApiClient.UnitTests", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach" 24 | } 25 | ] 26 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "markdownlint.config": { 3 | "MD028": false, 4 | "MD025": { 5 | "front_matter_title": "" 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/tests/Ardalis.ApiClient.UnitTests/Ardalis.ApiClient.UnitTests.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/tests/Ardalis.ApiClient.UnitTests/Ardalis.ApiClient.UnitTests.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/tests/Ardalis.ApiClient.UnitTests/Ardalis.ApiClient.UnitTests.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /Ardalis.ApiClient.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31729.503 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{93E1F1F2-932D-4658-8750-676B33FE0496}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{7487509D-1FEE-42D5-8D9C-E13A3566BDB6}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ardalis.ApiClient", "src\Ardalis.ApiClient\Ardalis.ApiClient.csproj", "{7C8299B7-0766-453A-833C-29C295905A3A}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ardalis.ApiClient.UnitTests", "tests\Ardalis.ApiClient.UnitTests\Ardalis.ApiClient.UnitTests.csproj", "{6A6253CE-39BC-4C9D-8206-0B0279635B19}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {7C8299B7-0766-453A-833C-29C295905A3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {7C8299B7-0766-453A-833C-29C295905A3A}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {7C8299B7-0766-453A-833C-29C295905A3A}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {7C8299B7-0766-453A-833C-29C295905A3A}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {6A6253CE-39BC-4C9D-8206-0B0279635B19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {6A6253CE-39BC-4C9D-8206-0B0279635B19}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {6A6253CE-39BC-4C9D-8206-0B0279635B19}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {6A6253CE-39BC-4C9D-8206-0B0279635B19}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {7C8299B7-0766-453A-833C-29C295905A3A} = {93E1F1F2-932D-4658-8750-676B33FE0496} 34 | {6A6253CE-39BC-4C9D-8206-0B0279635B19} = {7487509D-1FEE-42D5-8D9C-E13A3566BDB6} 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {03C7CB95-035C-459C-BE5F-F9710E462C53} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Steve Smith 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![NuGet](https://img.shields.io/nuget/v/Ardalis.ApiClient.svg)](https://www.nuget.org/packages/Ardalis.ApiClient)[![NuGet](https://img.shields.io/nuget/dt/Ardalis.ApiClient.svg)](https://www.nuget.org/packages/Ardalis.ApiClient) 3 | 4 | # Ardalis.ApiClient 5 | 6 | Some classes to make working with APIs easier. 7 | For big example how to use ApiClient please visit [DevBetter](https://github.com/DevBetterCom/DevBetterWeb/tree/main/src/DevBetterWeb.Vimeo/Services/VideoServices) 8 | 9 | 10 | ## Give a Star! :star: 11 | 12 | If you like or are using this project to learn or start your solution, please give it a star. Thanks! 13 | 14 | ## Credits 15 | 16 | Big thanks to [all of the great contributors to this project](https://github.com/ardalis/Ardalis.ApiClient/graphs/contributors)! 17 | 18 | ## Getting Started 19 | 20 | Install [Ardalis.ApiClient](https://nuget.org/Ardalis.ApiClient) from Nuget using: 21 | 22 | (in Visual Studio) 23 | 24 | ```powershell 25 | Install-Package Ardalis.ApiClient 26 | ``` 27 | 28 | (using the dotnet cli) 29 | 30 | ```powershell 31 | dotnet add package Ardalis.ApiClient 32 | ``` 33 | 34 | In `Startup.cs` (or wherever you configure your services) add the following code. Change the base address to be the base URL where your APIs are hosted. 35 | 36 | ```csharp 37 | public void ConfigureServices(IServiceCollection services) 38 | { 39 | .... 40 | services.AddScoped(sp => HttpClientBuilder()) 41 | services.AddScoped(); 42 | services.AddScoped(); 43 | .... 44 | } 45 | 46 | private static HttpClient HttpClientBuilder() 47 | { 48 | var httpClient = new HttpClient 49 | { 50 | BaseAddress = new Uri("https://example.com") 51 | }; 52 | 53 | return httpClient; 54 | } 55 | ``` 56 | 57 | Create a service file called `AddVideoService.cs` which is designed to call a particular API endpoint: 58 | 59 | ```csharp 60 | public class AddVideoService : BaseAsyncApiCaller 61 | .WithRequest 62 | .WithResponse 63 | { 64 | private readonly HttpService _httpService; 65 | private readonly ILogger _logger; 66 | 67 | public AddVideoService(HttpService httpService, ILogger logger) 68 | { 69 | _httpService = httpService; 70 | _logger = logger; 71 | } 72 | 73 | public override async Task> ExecuteAsync(VideoRequest request, 74 | CancellationToken cancellationToken = default) 75 | { 76 | var uri = $"videos/add"; 77 | try 78 | { 79 | var response = await _httpService.HttpPostAsync(uri, request); 80 | 81 | return response; 82 | } 83 | catch (Exception exception) 84 | { 85 | _logger.LogError(exception); 86 | return HttpResponse.FromException(exception.Message); 87 | } 88 | } 89 | } 90 | ``` 91 | 92 | Call the service in Blazor: 93 | 94 | ```csharp 95 | [Inject] 96 | AddVideoService AddVideoService { get; set; } 97 | 98 | private async Task AddVideoAsync() 99 | { 100 | VideoRequest videoToAdd = new VideoRequest() 101 | { 102 | Title = Title, 103 | CreatedDate = CreatedDate 104 | }; 105 | 106 | var result = await AddVideoService.ExecuteAsync(videoToAdd); 107 | if (result.Code != System.Net.HttpStatusCode.OK) return false; 108 | 109 | return result.Data; 110 | } 111 | ``` 112 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/Ardalis.ApiClient.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | Ardalis.ApiClient 6 | Ardalis.ApiClient 7 | false 8 | Steve Smith (@ardalis); Shady Nagy (@ShadyNagy_) 9 | Ardalis.com 10 | https://github.com/ardalis/Ardalis.ApiClient 11 | Api Client methods. 12 | Api Client methods. 13 | https://github.com/ardalis/Ardalis.ApiClient 14 | api client extensions extension method methods c# .net dotnet 15 | HttpPostByFormAsync has been added to support string return. 16 | 0.2.3 17 | Ardalis.ApiClient 18 | icon.png 19 | true 20 | true 21 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb 22 | 8.0 23 | LICENSE.txt 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/BaseApiCaller.cs: -------------------------------------------------------------------------------- 1 | namespace Ardalis.ApiClient 2 | { 3 | /// 4 | /// A base class for an api caller that accepts parameters. 5 | /// 6 | /// 7 | /// 8 | public static class BaseApiCaller 9 | { 10 | public static class WithRequest 11 | { 12 | public abstract class WithResponse 13 | { 14 | public abstract HttpResponse Execute(TRequest request); 15 | } 16 | 17 | public abstract class WithoutResponse 18 | { 19 | public abstract HttpResponse Execute(TRequest request); 20 | } 21 | } 22 | 23 | public static class WithoutRequest 24 | { 25 | public abstract class WithResponse 26 | { 27 | public abstract HttpResponse Execute(); 28 | } 29 | 30 | public abstract class WithoutResponse 31 | { 32 | public abstract HttpResponse Execute(); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/BaseAsyncApiCaller.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | namespace Ardalis.ApiClient 5 | { 6 | /// 7 | /// A base class for an api caller that accepts parameters. 8 | /// 9 | /// 10 | /// 11 | public static class BaseAsyncApiCaller 12 | { 13 | public static class WithRequest 14 | { 15 | public abstract class WithResponse 16 | { 17 | public abstract Task> ExecuteAsync( 18 | TRequest request, 19 | CancellationToken cancellationToken = default 20 | ); 21 | } 22 | 23 | public abstract class WithoutResponse 24 | { 25 | public abstract Task ExecuteAsync( 26 | TRequest request, 27 | CancellationToken cancellationToken = default 28 | ); 29 | } 30 | } 31 | 32 | public static class WithoutRequest 33 | { 34 | public abstract class WithResponse 35 | { 36 | public abstract Task> ExecuteAsync( 37 | CancellationToken cancellationToken = default 38 | ); 39 | } 40 | 41 | public abstract class WithoutResponse 42 | { 43 | public abstract Task ExecuteAsync( 44 | CancellationToken cancellationToken = default 45 | ); 46 | } 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/DictionaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Ardalis.ApiClient 4 | { 5 | public static class DictionaryExtensions 6 | { 7 | public static void AddIfNotNull(this Dictionary dictionary, T key, T2 value) 8 | { 9 | if (value != null) 10 | { 11 | dictionary.Add(key, value); 12 | } 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/HttpResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | namespace Ardalis.ApiClient 9 | { 10 | public class HttpResponse 11 | { 12 | public string Text { get; } 13 | public HttpStatusCode Code { get; } 14 | public IActionResult ActionResult => new StatusCodeResult((int)Code); 15 | public Dictionary Headers { get; } = new Dictionary(); 16 | public HttpResponseHeaders ResponseHeaders { get; private set; } 17 | 18 | public HttpResponse(HttpStatusCode code) 19 | { 20 | Code = code; 21 | } 22 | public HttpResponse(string result, HttpStatusCode code) 23 | { 24 | Text = result; 25 | Code = code; 26 | } 27 | 28 | public HttpResponse(HttpStatusCode code, HttpResponseHeaders headers) : this(code) 29 | { 30 | foreach (var header in headers) 31 | { 32 | Headers.Add(header.Key, header.Value.ToArray()); 33 | } 34 | } 35 | 36 | public void SetResponseHeaders(HttpResponseHeaders responseHeaders) 37 | { 38 | ResponseHeaders = responseHeaders; 39 | } 40 | 41 | public string GetFirstHeader(string key) 42 | { 43 | Headers.TryGetValue(key, out var allValues); 44 | 45 | return allValues?.FirstOrDefault(); 46 | } 47 | 48 | public string[] GetHeader(string key) 49 | { 50 | Headers.TryGetValue(key, out var allValues); 51 | 52 | return allValues; 53 | } 54 | 55 | public HttpResponse(HttpResponseMessage result) 56 | { 57 | var textResult = result.Content.ReadAsStringAsync().Result; 58 | 59 | Code = result.StatusCode; 60 | Text = textResult; 61 | Headers = new Dictionary(); 62 | 63 | foreach (var header in result.Headers) 64 | { 65 | Headers.Add(header.Key, header.Value.ToArray()); 66 | } 67 | } 68 | 69 | public static HttpResponse FromHttpResponseMessage(HttpResponseMessage result) 70 | { 71 | return new HttpResponse(result); 72 | } 73 | 74 | public static HttpResponse FromHttpResponseMessage(HttpStatusCode code) 75 | { 76 | return new HttpResponse(code); 77 | } 78 | 79 | public static HttpResponse FromHttpResponseMessage(HttpStatusCode code, HttpResponseHeaders headers) 80 | { 81 | return new HttpResponse(code, headers); 82 | } 83 | 84 | public static HttpResponse FromException(string result) 85 | { 86 | return new HttpResponse(result, HttpStatusCode.InternalServerError); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/HttpResponseGeneric.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Text.Json; 8 | using System.Threading.Tasks.Sources; 9 | using DevBetter.JsonExtensions; 10 | using DevBetter.JsonExtensions.Extensions; 11 | using Microsoft.AspNetCore.Mvc; 12 | 13 | namespace Ardalis.ApiClient 14 | { 15 | public class HttpResponse 16 | { 17 | public T Data { get; private set; } 18 | public string Text { get; } 19 | public HttpStatusCode Code { get; } 20 | 21 | public IActionResult ActionResult => new StatusCodeResult((int) Code); 22 | 23 | public Dictionary Headers { get; } = new Dictionary(); 24 | public HttpResponseHeaders ResponseHeaders { get; private set; } 25 | 26 | public void SetResponseHeaders(HttpResponseHeaders responseHeaders) 27 | { 28 | ResponseHeaders = responseHeaders; 29 | } 30 | 31 | public HttpResponse(HttpStatusCode code) 32 | { 33 | Code = code; 34 | } 35 | 36 | public HttpResponse(string result, HttpStatusCode code) 37 | { 38 | Text = result; 39 | Code = code; 40 | } 41 | 42 | public HttpResponse(T result, HttpStatusCode code) 43 | { 44 | Data = result; 45 | Code = code; 46 | } 47 | 48 | public HttpResponse(T result, HttpStatusCode code, HttpResponseHeaders headers) : this(result, code) 49 | { 50 | foreach (var header in headers) 51 | { 52 | Headers.Add(header.Key, header.Value.ToArray()); 53 | } 54 | } 55 | 56 | public string GetFirstHeader(string key) 57 | { 58 | Headers.TryGetValue(key, out var allValues); 59 | 60 | return allValues?.FirstOrDefault(); 61 | } 62 | 63 | public string[] GetHeader(string key) 64 | { 65 | Headers.TryGetValue(key, out var allValues); 66 | 67 | return allValues; 68 | } 69 | 70 | public HttpResponse(HttpResponseMessage result) 71 | { 72 | var textResult = result.Content.ReadAsStringAsync().Result; 73 | 74 | if (typeof(T).IsValueType) 75 | { 76 | Data = textResult.ConvertTo(); 77 | } 78 | else 79 | { 80 | var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; 81 | options.SetMissingMemberHandling(MissingMemberHandling.Ignore); 82 | 83 | var data = JsonSerializer.Deserialize(textResult, options); 84 | 85 | Data = data; 86 | } 87 | 88 | Code = result.StatusCode; 89 | Text = textResult; 90 | Headers = new Dictionary(); 91 | 92 | foreach (var header in result.Headers) 93 | { 94 | Headers.Add(header.Key, header.Value.ToArray()); 95 | } 96 | } 97 | 98 | public void SetData(T data) 99 | { 100 | Data = data; 101 | } 102 | 103 | public static HttpResponse FromHttpResponseMessage(HttpResponseMessage result) 104 | { 105 | return new HttpResponse(result); 106 | } 107 | 108 | public static HttpResponse FromHttpResponseMessage(T result, HttpStatusCode code) 109 | { 110 | return new HttpResponse(result, code); 111 | } 112 | 113 | public static HttpResponse FromHttpResponseMessage(HttpStatusCode code) 114 | { 115 | return new HttpResponse(code); 116 | } 117 | 118 | public static HttpResponse FromHttpResponseMessage(T result, HttpStatusCode code, HttpResponseHeaders headers) 119 | { 120 | return new HttpResponse(result, code, headers); 121 | } 122 | 123 | public static HttpResponse FromException(string result) 124 | { 125 | return new HttpResponse(result, HttpStatusCode.InternalServerError); 126 | } 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/HttpService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Text; 8 | using System.Text.Json; 9 | using System.Threading; 10 | using System.Threading.Tasks; 11 | using Microsoft.AspNetCore.WebUtilities; 12 | 13 | namespace Ardalis.ApiClient 14 | { 15 | public class HttpService 16 | { 17 | public HttpClient HttpClient { get; private set; } 18 | private string ApiBaseUrl => HttpClient.BaseAddress == null ? string.Empty: HttpClient.BaseAddress.ToString(); 19 | 20 | public HttpRequestHeaders RequestHeaders => HttpClient.DefaultRequestHeaders; 21 | 22 | public HttpService(HttpClient httpClient) 23 | { 24 | HttpClient = httpClient; 25 | } 26 | 27 | public void ResetHttp(string baseUri=null, string accept=null) 28 | { 29 | Uri baseUriToAdd = null; 30 | 31 | if (baseUri == null) 32 | { 33 | baseUriToAdd = HttpClient.BaseAddress; 34 | } 35 | else 36 | { 37 | baseUriToAdd = new Uri(baseUri); 38 | } 39 | 40 | var acceptToAdd = accept; 41 | if (string.IsNullOrEmpty(accept)) 42 | { 43 | acceptToAdd = HttpClient.DefaultRequestHeaders.Accept.First()?.ToString(); 44 | } 45 | 46 | SetBaseUri(acceptToAdd, baseUriToAdd); 47 | } 48 | 49 | public void ResetBaseUri() 50 | { 51 | var acceptToAdd = HttpClient.DefaultRequestHeaders.Accept.First()?.ToString(); 52 | 53 | SetBaseUri(acceptToAdd); 54 | } 55 | 56 | public void SetBaseUri(string accept, Uri baseUriToAdd=null) 57 | { 58 | var token = GetFirstHeader("Authorization"); 59 | var timeout = HttpClient.Timeout; 60 | 61 | HttpClient = new HttpClient(); 62 | if (baseUriToAdd != null) 63 | { 64 | HttpClient.BaseAddress = baseUriToAdd; 65 | } 66 | HttpClient.DefaultRequestHeaders.Add("accept", accept); 67 | HttpClient.DefaultRequestHeaders.Add("Authorization", token); 68 | HttpClient.Timeout = timeout; 69 | } 70 | 71 | public void AddHeader(string key, string value) 72 | { 73 | if (HttpClient.DefaultRequestHeaders.Contains(key)) 74 | { 75 | HttpClient.DefaultRequestHeaders.Remove(key); 76 | } 77 | HttpClient.DefaultRequestHeaders.Add(key, value); 78 | } 79 | 80 | public string GetFirstHeader(string key) 81 | { 82 | var allValues = HttpClient.DefaultRequestHeaders.GetValues(key); 83 | 84 | return allValues.FirstOrDefault(); 85 | } 86 | 87 | public string[] GetHeader(string key) 88 | { 89 | var allValues = HttpClient.DefaultRequestHeaders.GetValues(key); 90 | 91 | return allValues.ToArray(); 92 | } 93 | 94 | public void SetTimeout(int units, TimeoutType timeType = TimeoutType.Seconds) 95 | { 96 | if(timeType == TimeoutType.Seconds) 97 | { 98 | HttpClient.Timeout = TimeSpan.FromSeconds(units); 99 | } 100 | else if(timeType == TimeoutType.Minutes) 101 | { 102 | HttpClient.Timeout = TimeSpan.FromMinutes(units); 103 | } 104 | else if (timeType == TimeoutType.Hours) 105 | { 106 | HttpClient.Timeout = TimeSpan.FromHours(units); 107 | } 108 | } 109 | 110 | public void SetAuthorization(string value) 111 | { 112 | HttpClient.DefaultRequestHeaders.Remove("Authorization"); 113 | HttpClient.DefaultRequestHeaders.Add("Authorization", $"bearer {value}"); 114 | } 115 | 116 | public void SetDefaultTimeout() 117 | { 118 | HttpClient.Timeout = TimeSpan.FromSeconds(60); 119 | } 120 | 121 | public async Task> HttpGetAsync(string uri, CancellationToken cancellationToken = default) 122 | where T : class 123 | { 124 | var uriToSend = $"{ApiBaseUrl}{uri}"; 125 | 126 | var result = await HttpClient.GetAsync(uriToSend, cancellationToken); 127 | if (!result.IsSuccessStatusCode) 128 | { 129 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 130 | } 131 | 132 | var response = HttpResponse.FromHttpResponseMessage(result); 133 | response.SetResponseHeaders(result.Headers); 134 | 135 | return response; 136 | } 137 | 138 | public async Task> HttpGetAsync(string uri, Dictionary query, CancellationToken cancellationToken = default) 139 | where T : class 140 | { 141 | var uriToSend = $"{ApiBaseUrl}{QueryHelpers.AddQueryString(uri, query)}"; 142 | 143 | var result = await HttpClient.GetAsync(uriToSend, cancellationToken); 144 | if (!result.IsSuccessStatusCode) 145 | { 146 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 147 | } 148 | 149 | var response = HttpResponse.FromHttpResponseMessage(result); 150 | response.SetResponseHeaders(result.Headers); 151 | 152 | return response; 153 | } 154 | 155 | public Task> HttpDeleteAsync(string uri, object id, CancellationToken cancellationToken = default) 156 | where T : class 157 | { 158 | return HttpDeleteAsync($"{uri}/{id}", cancellationToken); 159 | } 160 | 161 | public async Task> HttpDeleteAsync(string uri, CancellationToken cancellationToken = default) 162 | where T : class 163 | { 164 | var result = await HttpClient.DeleteAsync($"{ApiBaseUrl}{uri}", cancellationToken); 165 | if (!result.IsSuccessStatusCode) 166 | { 167 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 168 | } 169 | 170 | var response = HttpResponse.FromHttpResponseMessage(result); 171 | response.SetResponseHeaders(result.Headers); 172 | 173 | return response; 174 | } 175 | 176 | public async Task> HttpDeleteAsync(string uri, CancellationToken cancellationToken = default) 177 | { 178 | var result = await HttpClient.DeleteAsync($"{ApiBaseUrl}{uri}", cancellationToken); 179 | if (!result.IsSuccessStatusCode) 180 | { 181 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 182 | } 183 | 184 | var response = HttpResponse.FromHttpResponseMessage(true, result.StatusCode, result.Headers); 185 | response.SetResponseHeaders(result.Headers); 186 | 187 | return response; 188 | } 189 | 190 | public async Task> HttpPostAsync(string uri, object dataToSend, CancellationToken cancellationToken = default) 191 | where T : class 192 | { 193 | var content = ToJson(dataToSend); 194 | 195 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 196 | if (!result.IsSuccessStatusCode) 197 | { 198 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 199 | } 200 | 201 | var response = HttpResponse.FromHttpResponseMessage(result); 202 | response.SetResponseHeaders(result.Headers); 203 | 204 | return response; 205 | } 206 | 207 | public async Task HttpPostWithoutResponseAsync(string uri, object dataToSend, CancellationToken cancellationToken = default) 208 | { 209 | var content = ToJson(dataToSend); 210 | 211 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 212 | if (!result.IsSuccessStatusCode) 213 | { 214 | return false; 215 | } 216 | 217 | return true; 218 | } 219 | 220 | public async Task> HttpPostByQueryAsync(string uri, Dictionary query, CancellationToken cancellationToken = default) 221 | where T : class 222 | { 223 | var uriToSend = QueryHelpers.AddQueryString(uri, query); 224 | 225 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uriToSend}", null, cancellationToken); 226 | if (!result.IsSuccessStatusCode) 227 | { 228 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 229 | } 230 | 231 | var response = HttpResponse.FromHttpResponseMessage(result); 232 | response.SetResponseHeaders(result.Headers); 233 | 234 | return response; 235 | } 236 | 237 | public async Task> HttpPostByFormAsync(string uri, NameValueCollection query, CancellationToken cancellationToken = default) 238 | where T : class 239 | { 240 | var formContent = new FormUrlEncodedContent(ToListKeyValuePair(query).ToArray()); 241 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uri}", formContent, cancellationToken); 242 | if (!result.IsSuccessStatusCode) 243 | { 244 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 245 | } 246 | 247 | var response = HttpResponse.FromHttpResponseMessage(result); 248 | response.SetResponseHeaders(result.Headers); 249 | 250 | return response; 251 | } 252 | 253 | public async Task HttpPostByFormAsync(string uri, NameValueCollection query, CancellationToken cancellationToken = default) 254 | { 255 | var formContent = new FormUrlEncodedContent(ToListKeyValuePair(query).ToArray()); 256 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uri}", formContent, cancellationToken); 257 | if (!result.IsSuccessStatusCode) 258 | { 259 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 260 | } 261 | 262 | var response = HttpResponse.FromHttpResponseMessage(result); 263 | response.SetResponseHeaders(result.Headers); 264 | 265 | return response; 266 | } 267 | 268 | public async Task> HttpPostByStringAsync(string uri, string body, CancellationToken cancellationToken = default) 269 | where T : class 270 | { 271 | 272 | var result = await HttpClient.PostAsync($"{ApiBaseUrl}{uri}", new StringContent(body), cancellationToken); 273 | if (!result.IsSuccessStatusCode) 274 | { 275 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 276 | } 277 | 278 | var response = HttpResponse.FromHttpResponseMessage(result); 279 | response.SetResponseHeaders(result.Headers); 280 | 281 | return response; 282 | } 283 | 284 | public async Task> HttpPutJsonAsync(string uri, object dataToSend, CancellationToken cancellationToken = default) 285 | where T : class 286 | { 287 | var content = ToJson(dataToSend); 288 | 289 | var result = await HttpClient.PutAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 290 | if (!result.IsSuccessStatusCode) 291 | { 292 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 293 | } 294 | 295 | var response = HttpResponse.FromHttpResponseMessage(result); 296 | response.SetResponseHeaders(result.Headers); 297 | 298 | return response; 299 | } 300 | 301 | public async Task> HttpPatchAsync(string uri, object dataToSend, CancellationToken cancellationToken = default) 302 | where T : class 303 | { 304 | var content = ToJson(dataToSend); 305 | 306 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 307 | if (!result.IsSuccessStatusCode) 308 | { 309 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 310 | } 311 | 312 | var response = HttpResponse.FromHttpResponseMessage(result); 313 | response.SetResponseHeaders(result.Headers); 314 | 315 | return response; 316 | } 317 | 318 | public async Task> HttpPatchWithoutResponseAsync(string uri, object dataToSend, CancellationToken cancellationToken = default) 319 | { 320 | var content = ToJson(dataToSend); 321 | 322 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 323 | if (!result.IsSuccessStatusCode) 324 | { 325 | return HttpResponse.FromHttpResponseMessage(false, result.StatusCode); 326 | } 327 | 328 | var response = HttpResponse.FromHttpResponseMessage(true, result.StatusCode); 329 | response.SetResponseHeaders(result.Headers); 330 | 331 | return response; 332 | } 333 | 334 | public async Task> HttpPatchBytesAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 335 | where T : class 336 | { 337 | var content = new ByteArrayContent(dataToSend); 338 | 339 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 340 | if (!result.IsSuccessStatusCode) 341 | { 342 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 343 | } 344 | 345 | var response = HttpResponse.FromHttpResponseMessage(result); 346 | response.SetResponseHeaders(result.Headers); 347 | 348 | return response; 349 | } 350 | 351 | public async Task> HttpPatchBytesAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 352 | { 353 | ByteArrayContent content = null; 354 | if (dataToSend != null) 355 | { 356 | content = new ByteArrayContent(dataToSend); 357 | } 358 | 359 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 360 | if (!result.IsSuccessStatusCode) 361 | { 362 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 363 | } 364 | 365 | var response = HttpResponse.FromHttpResponseMessage(true, result.StatusCode); 366 | response.SetResponseHeaders(result.Headers); 367 | 368 | return response; 369 | } 370 | 371 | public async Task> HttpPatchBytesAsync(string uri, ByteArrayContent content, CancellationToken cancellationToken = default) 372 | { 373 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 374 | if (!result.IsSuccessStatusCode) 375 | { 376 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 377 | } 378 | 379 | var response = HttpResponse.FromHttpResponseMessage(true, result.StatusCode); 380 | response.SetResponseHeaders(result.Headers); 381 | 382 | return response; 383 | } 384 | 385 | public async Task HttpPatchBytesWithoutResponseAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 386 | { 387 | var content = new ByteArrayContent(dataToSend); 388 | 389 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 390 | if (!result.IsSuccessStatusCode) 391 | { 392 | return false; 393 | } 394 | 395 | return true; 396 | } 397 | 398 | public async Task HttpPatchBytesWithoutResponseAsync(string uri, ByteArrayContent content, CancellationToken cancellationToken = default) 399 | { 400 | var result = await HttpClient.PatchAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 401 | if (!result.IsSuccessStatusCode) 402 | { 403 | return false; 404 | } 405 | 406 | return true; 407 | } 408 | 409 | public async Task> HttpPutBytesAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 410 | where T : class 411 | { 412 | var content = new ByteArrayContent(dataToSend); 413 | 414 | var result = await HttpClient.PutAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 415 | if (!result.IsSuccessStatusCode) 416 | { 417 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 418 | } 419 | 420 | var response = HttpResponse.FromHttpResponseMessage(result); 421 | response.SetResponseHeaders(result.Headers); 422 | 423 | return response; 424 | 425 | } 426 | 427 | public async Task> HttpPutBytesAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 428 | { 429 | ByteArrayContent content = null; 430 | if (dataToSend != null) 431 | { 432 | content = new ByteArrayContent(dataToSend); 433 | } 434 | 435 | var result = await HttpClient.PutAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 436 | if (!result.IsSuccessStatusCode) 437 | { 438 | return HttpResponse.FromHttpResponseMessage(result.StatusCode); 439 | } 440 | 441 | var response = HttpResponse.FromHttpResponseMessage(true, result.StatusCode); 442 | response.SetResponseHeaders(result.Headers); 443 | 444 | return response; 445 | } 446 | 447 | public async Task HttpPutBytesWithoutResponseAsync(string uri, byte[] dataToSend, CancellationToken cancellationToken = default) 448 | { 449 | var content = new ByteArrayContent(dataToSend); 450 | 451 | var result = await HttpClient.PutAsync($"{ApiBaseUrl}{uri}", content, cancellationToken); 452 | if (!result.IsSuccessStatusCode) 453 | { 454 | return false; 455 | } 456 | 457 | return true; 458 | } 459 | 460 | private StringContent ToJson(object obj) 461 | { 462 | return new StringContent(JsonSerializer.Serialize(obj), Encoding.UTF8, "application/json"); 463 | } 464 | 465 | public List> ToListKeyValuePair(NameValueCollection query) 466 | { 467 | var result = new List>(); 468 | foreach (var item in query.AllKeys.SelectMany(query.GetValues, (k, v) => new { key = k, value = v })) 469 | { 470 | result.Add(new KeyValuePair(item.key, item.value)); 471 | } 472 | 473 | return result; 474 | } 475 | } 476 | } 477 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/IBaseApiCaller.cs: -------------------------------------------------------------------------------- 1 | namespace Ardalis.ApiClient 2 | { 3 | public interface IBaseApiCaller 4 | { 5 | public HttpResponse Execute(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/License.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Steve Smith 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Ardalis.ApiClient 4 | { 5 | internal static class StringExtensions 6 | { 7 | internal static T ConvertTo(this string text) 8 | { 9 | if (typeof(T) == typeof(int) && int.TryParse(text, out var intResult)) 10 | { 11 | return (T)Convert.ChangeType(intResult, typeof(T)); 12 | } 13 | else if (typeof(T) == typeof(double) && double.TryParse(text, out var doubleResult)) 14 | { 15 | return (T)Convert.ChangeType(doubleResult, typeof(T)); 16 | } 17 | else if (typeof(T) == typeof(decimal) && decimal.TryParse(text, out var decimalResult)) 18 | { 19 | return (T)Convert.ChangeType(decimalResult, typeof(T)); 20 | } 21 | else if (typeof(T) == typeof(float) && float.TryParse(text, out var floatResult)) 22 | { 23 | return (T)Convert.ChangeType(floatResult, typeof(T)); 24 | } 25 | else if (typeof(T) == typeof(long) && long.TryParse(text, out var longResult)) 26 | { 27 | return (T)Convert.ChangeType(longResult, typeof(T)); 28 | } 29 | else if (typeof(T) == typeof(bool) && bool.TryParse(text, out var boolResult)) 30 | { 31 | return (T)Convert.ChangeType(boolResult, typeof(T)); 32 | } 33 | else if (typeof(T) == typeof(byte) && byte.TryParse(text, out var byteResult)) 34 | { 35 | return (T)Convert.ChangeType(byteResult, typeof(T)); 36 | } 37 | else if (typeof(T) == typeof(char) && char.TryParse(text, out var charResult)) 38 | { 39 | return (T)Convert.ChangeType(charResult, typeof(T)); 40 | } 41 | else if (typeof(T) == typeof(sbyte) && sbyte.TryParse(text, out var sbyteResult)) 42 | { 43 | return (T)Convert.ChangeType(sbyteResult, typeof(T)); 44 | } 45 | else if (typeof(T) == typeof(short) && short.TryParse(text, out var shortResult)) 46 | { 47 | return (T)Convert.ChangeType(shortResult, typeof(T)); 48 | } 49 | else if (typeof(T) == typeof(uint) && uint.TryParse(text, out var uintResult)) 50 | { 51 | return (T)Convert.ChangeType(uintResult, typeof(T)); 52 | } 53 | else if (typeof(T) == typeof(ulong) && ulong.TryParse(text, out var ulongResult)) 54 | { 55 | return (T)Convert.ChangeType(ulongResult, typeof(T)); 56 | } 57 | else if (typeof(T) == typeof(ushort) && ushort.TryParse(text, out var ushortResult)) 58 | { 59 | return (T)Convert.ChangeType(ushortResult, typeof(T)); 60 | } 61 | 62 | return (T)Convert.ChangeType(text, typeof(T)); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/TimeoutType.cs: -------------------------------------------------------------------------------- 1 | namespace Ardalis.ApiClient 2 | { 3 | public enum TimeoutType 4 | { 5 | Hours = 1, 6 | Minutes, 7 | Seconds 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Ardalis.ApiClient/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ardalis/Ardalis.ApiClient/db85dcd858edaf603768866e57295321ac45a0e3/src/Ardalis.ApiClient/icon.png -------------------------------------------------------------------------------- /tests/Ardalis.ApiClient.UnitTests/Ardalis.ApiClient.UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /tests/Ardalis.ApiClient.UnitTests/DictionaryAddIfNotNull.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Xunit; 4 | 5 | namespace Ardalis.ApiClient.UnitTests 6 | { 7 | public class DictionaryAddIfNotNull 8 | { 9 | private Dictionary _dictionary = new(); 10 | 11 | [Fact] 12 | public void DoesNothingGivenNullValue() 13 | { 14 | _dictionary.AddIfNotNull("key", null); 15 | 16 | Assert.Empty(_dictionary.Values); 17 | } 18 | 19 | [Fact] 20 | public void AddsNonNullValue() 21 | { 22 | _dictionary.AddIfNotNull("key", "val"); 23 | 24 | var result = _dictionary["key"]; 25 | 26 | Assert.Equal("val", result); 27 | } 28 | } 29 | } 30 | --------------------------------------------------------------------------------