├── .gitattributes ├── .github ├── dependabot.yml └── workflows │ └── dotnet.yml ├── .gitignore ├── .vscode ├── extensions.json ├── settings.json └── tasks.json ├── CONTRIBUTING.md ├── DotnetFetch.sln ├── LICENSE ├── README.md ├── src └── DotnetFetch │ ├── CorsException.cs │ ├── DotnetFetch.csproj │ ├── GlobalFetch.cs │ ├── InvalidCharsetException.cs │ ├── Models │ ├── FetchOptions.cs │ └── Response.cs │ ├── Obsolete │ ├── FetchCorsException.cs │ └── FetchInvalidCharsetException.cs │ └── Serialization │ ├── DefaultJsonSerializer.cs │ └── ISerializer.cs └── test └── DotnetFetch.Tests ├── DotnetFetch.Tests.csproj ├── FetchTests.cs ├── Serialization └── DefaultJsonSerializerTests.cs └── Usings.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "nuget" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: .NET 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Setup .NET 17 | uses: actions/setup-dotnet@v3 18 | with: 19 | dotnet-version: 6.0.x 20 | - name: Restore dependencies 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --no-restore 24 | - name: Test 25 | run: dotnet test --no-build --verbosity normal 26 | -------------------------------------------------------------------------------- /.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/main/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 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-dotnettools.csharp", 4 | "ms-dotnettools.csdevkit", 5 | "ms-dotnettools.vscodeintellicode-csharp" 6 | ] 7 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "dotnet.defaultSolution": "DotnetFetch.sln" 3 | } -------------------------------------------------------------------------------- /.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 | "/property:GenerateFullPaths=true", 11 | "/consoleloggerparameters:NoSummary" 12 | ], 13 | "problemMatcher": "$msCompile" 14 | }, 15 | { 16 | "label": "publish", 17 | "command": "dotnet", 18 | "type": "process", 19 | "args": [ 20 | "publish", 21 | "${workspaceFolder}/src/DotnetFetch/DotnetFetch.csproj", 22 | "/property:GenerateFullPaths=true", 23 | "/consoleloggerparameters:NoSummary" 24 | ], 25 | "problemMatcher": "$msCompile" 26 | } 27 | ] 28 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | ![Contributors](https://img.shields.io/github/contributors/victoriaquasar/DotnetFetch) 4 | 5 | ## Making a Pull Request 6 | 7 | - Fork this repository 8 | - Take "main" or "development" as base 9 | - Make your changes and make your pull request 10 | 11 | ## Pull Request model 12 | 13 | - **Summary**: what is this pull request doing? Solving a problem? Implementing new functions? 14 | - **Tests** (optional): reference your tests and make sure that they are passing 15 | 16 |
17 | 18 | All the pull requests will be reviewed and approved as as possible, the project is being actively maintained and is accepting any useful contribution. 19 | -------------------------------------------------------------------------------- /DotnetFetch.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.3.32819.101 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DotnetFetch", "src\DotnetFetch\DotnetFetch.csproj", "{D547B64B-13DB-4565-B7E4-082F7675F625}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotnetFetch.Tests", "test\DotnetFetch.Tests\DotnetFetch.Tests.csproj", "{C6D2D960-B361-4A36-94C9-6703D82C0D39}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {D547B64B-13DB-4565-B7E4-082F7675F625}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {D547B64B-13DB-4565-B7E4-082F7675F625}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {D547B64B-13DB-4565-B7E4-082F7675F625}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {D547B64B-13DB-4565-B7E4-082F7675F625}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {C6D2D960-B361-4A36-94C9-6703D82C0D39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {C6D2D960-B361-4A36-94C9-6703D82C0D39}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {C6D2D960-B361-4A36-94C9-6703D82C0D39}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {C6D2D960-B361-4A36-94C9-6703D82C0D39}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {5481EC28-0027-4A19-8E77-69AE700FC5D3} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Victória Rose 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 | # DotnetFetch 2 | 3 | - Simple .NET implementation of JavaScript fetch API. 4 | - Package is on [Nuget](https://www.nuget.org/packages/DotnetFetch/). 5 | - Following (partially) the [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch) specifications. 6 | 7 | ## Installation 8 | 9 | ```bash 10 | > Install-Package DotnetFetch 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```cs 16 | using static DotnetFetch.GlobalFetch; 17 | 18 | var result = await Fetch("https://jsonplaceholder.typicode.com/todos/1"); 19 | 20 | Console.WriteLine(result.Text()); 21 | ``` 22 | 23 | ```cs 24 | using static DotnetFetch.GlobalFetch; 25 | 26 | var result = await Fetch("https://jsonplaceholder.typicode.com/todos/1"); 27 | 28 | Console.WriteLine(result); 29 | ``` 30 | -------------------------------------------------------------------------------- /src/DotnetFetch/CorsException.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetFetch; 2 | 3 | /// 4 | /// Represents an exception thrown when a CORS error is detected. 5 | /// 6 | public class CorsException 7 | : Exception 8 | { 9 | /// 10 | /// Creates a new from the specified URL with a default message. 11 | /// 12 | /// The URL that caused the exception. 13 | public CorsException(string url) 14 | : base($"A CORS exception has occurred, check your request options.") => 15 | Url = url; 16 | 17 | /// 18 | /// Creates a new from the specified URL with a custom message. 19 | /// 20 | /// The URL that caused the exception. 21 | /// The message to use for the exception. 22 | public CorsException(string url, string message) 23 | : base(message) => 24 | Url = url; 25 | 26 | /// 27 | /// Gets or sets the URL that caused the exception. 28 | /// 29 | public string Url { get; } 30 | } 31 | -------------------------------------------------------------------------------- /src/DotnetFetch/DotnetFetch.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;net6.0 5 | 2.1.0 6 | victoriaquasar 7 | enable 8 | enable 9 | 10.0 10 | True 11 | DotnetFetch 12 | Simple .NET implementation of JavaScript fetch API 13 | LICENSE 14 | True 15 | https://github.com/victoriaquasar/DotnetFetch 16 | README.md 17 | 18 | 19 | 20 | 21 | 22 | True 23 | \ 24 | 25 | 26 | True 27 | \ 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/DotnetFetch/GlobalFetch.cs: -------------------------------------------------------------------------------- 1 | using DotnetFetch.Models; 2 | using System.Text; 3 | using System.Text.Json; 4 | using System.Text.Json.Nodes; 5 | using Microsoft.AspNetCore.WebUtilities; 6 | using System.Net.Http.Headers; 7 | 8 | namespace DotnetFetch 9 | { 10 | /// 11 | /// Defines methods for fetching resources from an external provider over the network. 12 | /// 13 | public static class GlobalFetch 14 | { 15 | /// 16 | /// Gets or sets whether or not the fetch method will throw a when a CORS error is detected. 17 | /// 18 | /// The default value is . 19 | public static bool EnableCorsException { get; set; } = false; 20 | private static HttpClient? _internalSingletonClient = null; 21 | 22 | /// 23 | /// Fetches a resource from an external provider over the network. 24 | /// 25 | /// The URL of the resource to fetch. 26 | /// The options to use when fetching the resource. 27 | /// A to cancel the request. 28 | /// An to use for the request. If , a new will be created. 29 | /// A object containing the response from the request. 30 | /// Thrown when a CORS error is detected and is . 31 | /// Thrown when an invalid charset is detected. 32 | public static async Task Fetch( 33 | string resource, 34 | JsonObject? options = default, 35 | CancellationToken cancellationToken = default, 36 | HttpClient? injectableClient = default 37 | ) 38 | { 39 | // Arrange: generating the FetchOptions object 40 | 41 | var fetchOptions = new FetchOptions( 42 | options?["headers"] ?? new JsonObject(), 43 | options?["body"]?.ToJsonString() ?? "", 44 | //get | post | delete | put | patch | head |options 45 | options?["method"]?.ToString() ?? "get", 46 | //cors | no-cors | same-origin 47 | options?["mode"]?.ToString() ?? "no-cors", 48 | //omit | same-origin | include 49 | options?["credentials"]?.ToString() ?? "same-origin", 50 | //default | no-store | reload | no-cache | force-cache | only-if-cached 51 | options?["cache"]?.ToString() ?? "default", 52 | //follow | manual // no support: error 53 | options?["redirect"]?.ToString() ?? "follow", 54 | (bool)(options?["keep-alive"] ?? false) 55 | ); 56 | 57 | // Arrange: will mount an HttpClient object based in the resource 58 | // and options, passed as arguments by the user, including handler 59 | // configuration 60 | 61 | HttpClientHandler httpHandler = 62 | new() { AllowAutoRedirect = fetchOptions.Redirect == "follow" }; 63 | 64 | HttpClient client; 65 | 66 | if (injectableClient != null) 67 | { 68 | client = injectableClient; 69 | 70 | if (injectableClient.BaseAddress is null) 71 | { 72 | client.BaseAddress = new Uri(resource); 73 | } 74 | } 75 | else 76 | { 77 | _internalSingletonClient = new HttpClient(); 78 | client = _internalSingletonClient; 79 | client.BaseAddress = new Uri(resource); 80 | } 81 | 82 | // Arrange: will mount and apply the headers dictionary with the headers 83 | // JsonObject (for now, dynamic as value type is the best approach here) 84 | 85 | var headersJson = fetchOptions.Headers.ToJsonString(); 86 | var headersBytes = new MemoryStream(Encoding.UTF8.GetBytes(headersJson)); 87 | var headersDictionary = await JsonSerializer.DeserializeAsync< 88 | Dictionary 89 | >(headersBytes, cancellationToken: cancellationToken); 90 | 91 | headersDictionary 92 | ?.ToList() 93 | .ForEach(header => client.DefaultRequestHeaders.Add(header.Key, header.Value)); 94 | 95 | // Arrange: will get the mode (cors) option to be passed as a 96 | // (Sec-Fetch-Mode) header 97 | 98 | client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", fetchOptions.Mode); 99 | 100 | // Arrange: will get the credentials option to be passed as a 101 | // (Access-Control-Allow-Credentials) header 102 | 103 | var credentialsHeader = (!(fetchOptions.Credentials == "omit")).ToString().ToLower(); 104 | client.DefaultRequestHeaders.Add("Access-Control-Allow-Credentials", credentialsHeader); 105 | 106 | // Arrange: will get the keep-alive option to be passed as a 107 | // (Connection-Close) header 108 | 109 | client.DefaultRequestHeaders.ConnectionClose = fetchOptions.KeepAlive; 110 | 111 | // Arrange: will get the cache option to be passed as a 112 | // (Cache-Control) header 113 | 114 | client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue 115 | { 116 | NoCache = fetchOptions.Cache == "default" || fetchOptions.Cache == "force-cache" 117 | }; 118 | 119 | // Arrange: will get the encoding (Accept-Charset) and mime type 120 | // (Content-Type) headers to be passed into the HttpClient request 121 | 122 | string acceptCharset = (headersDictionary ?? new()).TryGetValue( 123 | "Accept-Charset", 124 | out var _acceptCharset 125 | ) 126 | ? _acceptCharset 127 | : "utf-8"; 128 | 129 | var charset = acceptCharset.ToLowerInvariant() switch 130 | { 131 | "utf-8" => Encoding.UTF8, 132 | "utf-32" => Encoding.UTF32, 133 | "unicode" => Encoding.Unicode, 134 | _ => throw new FetchInvalidCharsetException(acceptCharset), 135 | }; 136 | 137 | string contentType = (headersDictionary ?? new()).TryGetValue( 138 | "Content-Type", 139 | out var _contentType 140 | ) 141 | ? _contentType 142 | : "text/plain"; 143 | 144 | // Arrange: will generate the StringContent object containing the body, 145 | // charset and content type to be passed directly to the HttpClient request, 146 | // then, check the argument http method and start the request 147 | 148 | var content = new StringContent(fetchOptions.Body, charset, contentType); 149 | 150 | var httpMethod = new HttpMethod(fetchOptions.Method.ToUpper()); 151 | var requestMessage = new HttpRequestMessage(httpMethod, resource) { Content = content }; 152 | 153 | var result = await client.SendAsync(requestMessage, cancellationToken); 154 | #if NETSTANDARD 155 | var resultBody = await result.Content.ReadAsStringAsync(); 156 | #else 157 | var resultBody = await result.Content.ReadAsStringAsync(cancellationToken); 158 | #endif 159 | var resultHeaders = result.Headers.ToDictionary(x => x.Key, x => (dynamic)x.Value); 160 | var status = (short)result.StatusCode; 161 | var statusText = ReasonPhrases.GetReasonPhrase(status); 162 | var ok = result.IsSuccessStatusCode; 163 | var bodyUsed = 164 | fetchOptions.Body != "" 165 | && fetchOptions.Method != "get" 166 | && fetchOptions.Method != "delete"; 167 | 168 | // Act: Checks for cors exceptions, surely, there is a better way 169 | // to check for CORS exceptions, a more complex research will be 170 | // made to create a more reliable solution 171 | 172 | if ( 173 | EnableCorsException && !ok 174 | || ( 175 | resultBody.ToLower().Contains("access-control") 176 | || resultBody.ToLower().Contains("cors") 177 | ) 178 | ) 179 | { 180 | throw new FetchCorsException(); 181 | } 182 | 183 | // Act: Creates a new Response object, based on "fetch" default 184 | // specification with base on MDN 185 | 186 | return new(resultBody, resultHeaders, status, statusText, ok, bodyUsed); 187 | } 188 | 189 | /// 190 | /// Fetches a resource from an external provider over the network. 191 | /// 192 | /// The type to deserialize the response body to. 193 | /// The URL of the resource to fetch. 194 | /// The options to use when fetching the resource. 195 | /// A to cancel the request. 196 | /// The deserialized response from the external provider. 197 | /// This method is a shorthand for with set to . 198 | /// 199 | public static async Task Fetch( 200 | string resource, 201 | JsonObject? options = default, 202 | CancellationToken cancellationToken = default 203 | ) 204 | { 205 | var response = await Fetch(resource, options, cancellationToken); 206 | var result = JsonSerializer.Deserialize(response.Body); 207 | 208 | return result!; 209 | } 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /src/DotnetFetch/InvalidCharsetException.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetFetch; 2 | 3 | /// 4 | /// Represents an exception thrown when an invalid charset is detected. 5 | /// 6 | public class InvalidCharsetException 7 | : Exception 8 | { 9 | /// 10 | /// Creates a new from the specified charset with a default message. 11 | /// 12 | /// The charset that caused the exception. 13 | public InvalidCharsetException(string charset) 14 | : base(message: "Invalid charset detected.") => 15 | Charset = charset; 16 | 17 | /// 18 | /// Creates a new from the specified charset with a custom message. 19 | /// 20 | /// The charset that caused the exception. 21 | /// The message to use for the exception. 22 | public InvalidCharsetException(string charset, string message) 23 | : base(message) => 24 | Charset = charset; 25 | 26 | /// 27 | /// Gets the charset that caused the exception. 28 | /// 29 | public string Charset { get; } 30 | } -------------------------------------------------------------------------------- /src/DotnetFetch/Models/FetchOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Nodes; 2 | 3 | namespace DotnetFetch.Models 4 | { 5 | /// 6 | /// Represents the options to use when fetching a resource from an external provider over the network. 7 | /// 8 | public class FetchOptions 9 | { 10 | /// 11 | /// Creates a new object. 12 | /// 13 | /// The headers to use when fetching the resource. 14 | /// The body to use when fetching the resource. 15 | /// The method to use when fetching the resource. 16 | /// The mode to use when fetching the resource. 17 | /// The credentials to use when fetching the resource. 18 | /// The cache to use when fetching the resource. 19 | /// The redirect to use when fetching the resource. 20 | /// Whether or not to keep the connection alive when fetching the resource. 21 | public FetchOptions( 22 | JsonNode headers, 23 | string body, 24 | string method, 25 | string mode, 26 | string credentials, 27 | string cache, 28 | string redirect, 29 | bool keepAlive 30 | ) 31 | { 32 | Headers = headers; 33 | Body = body; 34 | Method = method; 35 | Mode = mode; 36 | Credentials = credentials; 37 | Cache = cache; 38 | Redirect = redirect; 39 | KeepAlive = keepAlive; 40 | } 41 | 42 | /// 43 | /// Gets or sets the headers to use when fetching the resource. 44 | /// 45 | public JsonNode Headers { get; set; } 46 | 47 | /// 48 | /// Gets or sets the body to use when fetching the resource. 49 | /// 50 | public string Body { get; set; } 51 | 52 | /// 53 | /// Gets or sets the method to use when fetching the resource. 54 | /// 55 | public string Method { get; set; } 56 | 57 | /// 58 | /// Gets or sets the mode to use when fetching the resource. 59 | /// 60 | public string Mode { get; set; } 61 | 62 | /// 63 | /// Gets or sets the credentials to use when fetching the resource. 64 | /// 65 | public string Credentials { get; set; } 66 | 67 | /// 68 | /// Gets or sets the cache to use when fetching the resource. 69 | /// 70 | public string Cache { get; set; } 71 | 72 | /// 73 | /// Gets or sets the redirect to use when fetching the resource. 74 | /// 75 | public string Redirect { get; set; } 76 | 77 | /// 78 | /// Gets or sets whether or not to keep the connection alive when fetching the resource. 79 | /// 80 | public bool KeepAlive { get; set; } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/DotnetFetch/Models/Response.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Text.Json; 3 | using System.Text.Json.Nodes; 4 | 5 | namespace DotnetFetch.Models 6 | { 7 | /// 8 | /// Represents a response to a fetch request. 9 | /// 10 | public class Response 11 | { 12 | /// 13 | /// Creates a new object. 14 | /// 15 | /// The body of the response. 16 | /// The headers of the response. 17 | /// The status code of the response. 18 | /// The status text of the response. 19 | /// Whether or not the response was successful. 20 | /// Whether or not the body of the response has been used. 21 | public Response( 22 | string body, 23 | Dictionary headers, 24 | short status, 25 | string statusText, 26 | bool ok, 27 | bool bodyUsed 28 | ) 29 | { 30 | Body = body; 31 | Headers = headers; 32 | Status = status; 33 | StatusText = statusText; 34 | Ok = ok; 35 | BodyUsed = bodyUsed; 36 | } 37 | 38 | /// 39 | /// Gets or sets the body of the response. 40 | /// 41 | public string Body { get; set; } 42 | 43 | /// 44 | /// Gets or sets the headers of the response. 45 | /// 46 | public Dictionary Headers { get; set; } 47 | 48 | /// 49 | /// Gets or sets the status code of the response. 50 | /// 51 | public short Status { get; set; } 52 | 53 | /// 54 | /// Gets or sets the status text of the response. 55 | /// 56 | public string StatusText { get; set; } 57 | 58 | /// 59 | /// Gets or sets whether or not the response was successful. 60 | /// 61 | public bool Ok { get; set; } 62 | 63 | /// 64 | /// Gets or sets whether or not the body of the response has been used. 65 | /// 66 | public bool BodyUsed { get; set; } 67 | 68 | /// 69 | /// Deserializes the body of the response into a . 70 | /// 71 | /// A representing the body of the response. 72 | public JsonObject Json() => JsonSerializer.Deserialize(Body)!; 73 | 74 | /// 75 | /// Gets the body of the response as text. 76 | /// 77 | /// A string representing the body of the response. 78 | public string Text() => Body; 79 | 80 | /// 81 | /// Gets the body of the response as a byte array. 82 | /// 83 | /// A byte array representing the body of the response. 84 | public byte[] Blob() => Encoding.UTF8.GetBytes(Text()); 85 | 86 | /// 87 | /// Gets the body of the response as a byte array. 88 | /// 89 | /// A byte array representing the body of the response. 90 | public byte[] ArrayBuffer() => Blob(); 91 | 92 | /// 93 | /// Clones the response. 94 | /// 95 | /// A new object with the same properties as the original. 96 | public Response Clone() => new(Body, Headers, Status, StatusText, Ok, BodyUsed); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/DotnetFetch/Obsolete/FetchCorsException.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetFetch.Models 2 | { 3 | /// 4 | /// Represents an exception thrown when a CORS error is detected. 5 | /// 6 | /// This exception is a form of . 7 | /// 8 | [Obsolete(message: "This exception is obsolete and will be removed in a future version. Please use CorsException instead.")] 9 | public class FetchCorsException : ArgumentException 10 | { 11 | /// 12 | /// Creates a new with a default message. 13 | /// 14 | public FetchCorsException() 15 | : base("A CORS exception has occurred, check your request options.") { } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/DotnetFetch/Obsolete/FetchInvalidCharsetException.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetFetch.Models 2 | { 3 | /// 4 | /// Represents an exception thrown when an invalid charset is detected. 5 | /// 6 | /// This exception is a form of . 7 | /// 8 | [Obsolete(message: "This exception is obsolete and will be removed in a future version. Please use InvalidCharsetException instead.")] 9 | public class FetchInvalidCharsetException : ArgumentException 10 | { 11 | /// 12 | /// Creates a new with a default message. 13 | /// 14 | /// The invalid charset that was detected. 15 | public FetchInvalidCharsetException(string charset) : base($"Invalid charset: {charset}") 16 | { } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/DotnetFetch/Serialization/DefaultJsonSerializer.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | 3 | namespace DotnetFetch.Serialization; 4 | 5 | /// 6 | /// Represents the default used by DotnetFetch. 7 | /// 8 | public class DefaultJsonSerializer 9 | : ISerializer 10 | { 11 | /// 12 | /// Thrown when is null, empty, or whitespace. 13 | public T? Deserialize(string content) 14 | { 15 | if (string.IsNullOrWhiteSpace(content)) 16 | throw new ArgumentException(message: "The content cannot be null or whitespace.", paramName: nameof(content)); 17 | 18 | return JsonSerializer.Deserialize(content); 19 | } 20 | 21 | /// 22 | public string Serialize(T content) => 23 | JsonSerializer.Serialize(content); 24 | } -------------------------------------------------------------------------------- /src/DotnetFetch/Serialization/ISerializer.cs: -------------------------------------------------------------------------------- 1 | namespace DotnetFetch.Serialization; 2 | 3 | /// 4 | /// Defines methods for serializing and deserializing objects. 5 | /// 6 | public interface ISerializer 7 | { 8 | /// 9 | /// Deserializes a specified string into an object. 10 | /// 11 | /// The string to deserialize. 12 | /// The type of the object to deserialize into. 13 | /// The deserialized object. 14 | T? Deserialize(string content); 15 | 16 | /// 17 | /// Serializes a specified object into a string. 18 | /// 19 | /// The object to serialize. 20 | /// The type of the object to serialize. 21 | /// The serialized string. 22 | string Serialize(T content); 23 | } 24 | -------------------------------------------------------------------------------- /test/DotnetFetch.Tests/DotnetFetch.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | all 17 | 18 | 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | all 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /test/DotnetFetch.Tests/FetchTests.cs: -------------------------------------------------------------------------------- 1 | using static DotnetFetch.GlobalFetch; 2 | using DotnetFetch.Models; 3 | using System.Text.Json; 4 | using System.Text.Json.Nodes; 5 | 6 | namespace DotnetFetch.Tests 7 | { 8 | public class FetchTests 9 | { 10 | [Fact] 11 | public async void FetchBasicFunctionShouldWorkProperly() 12 | { 13 | var result = await Fetch("https://jsonplaceholder.typicode.com/todos/1"); 14 | var model = JsonSerializer.Deserialize>(result.Text())!; 15 | 16 | Assert.Equal(1, model["userId"].GetInt32()); 17 | Assert.Equal(1, model["id"].GetInt32()); 18 | Assert.Equal("delectus aut autem", model["title"].GetString()); 19 | Assert.False(model["completed"].GetBoolean()); 20 | } 21 | 22 | [Fact] 23 | public async void FetchGenericFunctionShouldWorkProperly() 24 | { 25 | var result = await Fetch>( 26 | "https://jsonplaceholder.typicode.com/todos/1" 27 | ); 28 | 29 | Assert.Equal(1, result["userId"].GetInt32()); 30 | Assert.Equal(1, result["id"].GetInt32()); 31 | Assert.Equal("delectus aut autem", result["title"].GetString()); 32 | Assert.False(result["completed"].GetBoolean()); 33 | } 34 | 35 | [Fact] 36 | public async Task FetchInvalidCharsetShouldThrowException() 37 | { 38 | var fetchOptions = new JsonObject 39 | { 40 | ["headers"] = new JsonObject() { ["Accept-Charset"] = "invalid" } 41 | }; 42 | 43 | await Assert.ThrowsAsync( 44 | () => Fetch("https://jsonplaceholder.typicode.com/todos/1", fetchOptions) 45 | ); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/DotnetFetch.Tests/Serialization/DefaultJsonSerializerTests.cs: -------------------------------------------------------------------------------- 1 | using DotnetFetch.Serialization; 2 | 3 | namespace DotnetFetch.Tests.Serialization; 4 | 5 | public class DefaultJsonSerializerTests 6 | { 7 | [Theory] 8 | [InlineData(null)] 9 | [InlineData("")] 10 | [InlineData(" ")] 11 | public void Deserialize_NullEmptyOrWhitespaceContent_ThrowsArgumentException(string content) 12 | { 13 | // Arrange 14 | DefaultJsonSerializer serializer = new(); 15 | 16 | // Act 17 | void TestAction() => serializer.Deserialize(content); 18 | 19 | // Assert 20 | Assert.Throws(TestAction); 21 | } 22 | 23 | [Fact] 24 | public void Deserialize_ValidContent_ReturnsDeserializedObject() 25 | { 26 | // Arrange 27 | DefaultJsonSerializer serializer = new(); 28 | string content = "{\"foo\":\"bar\"}"; 29 | 30 | // Act 31 | object? result = serializer.Deserialize(content); 32 | 33 | // Assert 34 | Assert.NotNull(result); 35 | } 36 | 37 | [Fact] 38 | public void Serialize_ValidObject_ReturnsSerializedString() 39 | { 40 | // Arrange 41 | DefaultJsonSerializer serializer = new(); 42 | object content = new { foo = "bar" }; 43 | 44 | // Act 45 | string result = serializer.Serialize(content); 46 | 47 | // Assert 48 | Assert.NotNull(result); 49 | } 50 | } -------------------------------------------------------------------------------- /test/DotnetFetch.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; 2 | --------------------------------------------------------------------------------