├── .DS_Store ├── HttpExtension ├── .DS_Store ├── HttpExtensionsBase.cs ├── HttpExtension.csproj ├── HttpExtensionResponse.cs ├── HttpSendExtensions.cs ├── HttpPutExtensions.cs ├── HttpGetExtensions.cs ├── HttpDeleteExtensions.cs └── HttpPostExtensions.cs ├── Resources └── helpersicon.png ├── GitVersion.yml ├── .mfractor └── HttpExtension.38bd8ed9-490a-40ce-9c6b-3168b9cd6999.db ├── HttpExtension.sln ├── .github └── workflows │ └── publishNuget.yml ├── .gitattributes ├── README.md └── .gitignore /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TBertuzzi/HttpExtension/HEAD/.DS_Store -------------------------------------------------------------------------------- /HttpExtension/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TBertuzzi/HttpExtension/HEAD/HttpExtension/.DS_Store -------------------------------------------------------------------------------- /Resources/helpersicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TBertuzzi/HttpExtension/HEAD/Resources/helpersicon.png -------------------------------------------------------------------------------- /GitVersion.yml: -------------------------------------------------------------------------------- 1 | next-version: 5.0.0 2 | branches: 3 | release: 4 | regex: releases?[/-] 5 | develop: 6 | tag: "pre" 7 | -------------------------------------------------------------------------------- /.mfractor/HttpExtension.38bd8ed9-490a-40ce-9c6b-3168b9cd6999.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TBertuzzi/HttpExtension/HEAD/.mfractor/HttpExtension.38bd8ed9-490a-40ce-9c6b-3168b9cd6999.db -------------------------------------------------------------------------------- /HttpExtension/HttpExtensionsBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using System.Threading.Tasks; 4 | using Newtonsoft.Json; 5 | 6 | public static partial class HttpExtensions 7 | { 8 | internal static async Task> GetResponse(HttpResponseMessage response) 9 | { 10 | var returnResponse = new HttpExtensionResponse(response.StatusCode); 11 | try 12 | { 13 | returnResponse.Content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); 14 | if (returnResponse.Content != null) 15 | returnResponse.Value = JsonConvert.DeserializeObject(returnResponse.Content); 16 | 17 | } 18 | catch (Exception ex) 19 | { 20 | returnResponse.Error = ex; 21 | } 22 | return returnResponse; 23 | } 24 | } -------------------------------------------------------------------------------- /HttpExtension.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28010.2046 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpExtension", "HttpExtension\HttpExtension.csproj", "{38BD8ED9-490A-40CE-9C6B-3168B9CD6999}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {38BD8ED9-490A-40CE-9C6B-3168B9CD6999}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {38BD8ED9-490A-40CE-9C6B-3168B9CD6999}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {38BD8ED9-490A-40CE-9C6B-3168B9CD6999}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {38BD8ED9-490A-40CE-9C6B-3168B9CD6999}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {C28104D5-FED0-467B-9FB8-6AF60185B41D} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /HttpExtension/HttpExtension.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | tbertuzzi 6 | KBits 7 | Extensions for HttpClient 8 | Copyright ©2024 KBits 9 | 10 | helpers http httpclient nethttp rest post get put delete async 11 | compatibility change to netstandard2.1 and package updates 12 | https://github.com/TBertuzzi/HttpExtension 13 | https://github.com/TBertuzzi/HttpExtension 14 | 15 | True 16 | 5.0.0 17 | 5.0.0.0 18 | 5.0.0.0 19 | helpersicon.png 20 | 5.0.0 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | True 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /HttpExtension/HttpExtensionResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Text; 5 | 6 | 7 | public sealed class HttpExtensionResponse 8 | { 9 | /// 10 | /// Gets the status code. 11 | /// 12 | public HttpStatusCode StatusCode { get; private set; } 13 | 14 | /// 15 | /// Gets the value. 16 | /// 17 | public T Value { get; set; } 18 | 19 | /// 20 | /// Gets the content. 21 | /// 22 | public string Content { get; set; } 23 | 24 | /// 25 | /// Gets the error. 26 | /// 27 | public Exception Error { get; set; } 28 | 29 | /// 30 | /// Initializes a new instance of the class. 31 | /// 32 | /// 33 | /// The value. 34 | /// 35 | /// 36 | /// The status code. 37 | /// 38 | public HttpExtensionResponse(T value, HttpStatusCode statusCode) 39 | { 40 | this.Value = value; 41 | this.StatusCode = statusCode; 42 | } 43 | 44 | /// 45 | /// Initializes a new instance of the class. 46 | /// 47 | /// 48 | /// The status code. 49 | /// 50 | /// 51 | /// The error. 52 | /// 53 | public HttpExtensionResponse(HttpStatusCode statusCode, Exception error = null) 54 | { 55 | this.StatusCode = statusCode; 56 | this.Error = error; 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /HttpExtension/HttpSendExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Threading.Tasks; 5 | using Polly.Retry; 6 | 7 | public static partial class HttpExtensions 8 | { 9 | public static async Task> SendAsync(this HttpClient httpClient, HttpRequestMessage request) 10 | { 11 | try 12 | { 13 | return await InternalSendAsync(httpClient, request); 14 | } 15 | catch (Exception ex) 16 | { 17 | return new HttpExtensionResponse( 18 | HttpStatusCode.InternalServerError, 19 | ex); 20 | } 21 | } 22 | 23 | public static async Task> SendAsync(this HttpClient httpClient, HttpRequestMessage request, 24 | AsyncRetryPolicy> policy) 25 | { 26 | return await policy.ExecuteAsync(async () => 27 | { 28 | return await InternalSendAsync(httpClient, request); 29 | }); 30 | } 31 | 32 | public static async Task> SendAsync(this HttpClient httpClient, HttpRequestMessage request, 33 | AsyncRetryPolicy policy) 34 | { 35 | return await policy.ExecuteAsync(async () => 36 | { 37 | return await InternalSendAsync(httpClient, request); 38 | }); 39 | } 40 | 41 | private static async Task> InternalSendAsync(HttpClient httpClient, HttpRequestMessage request) 42 | { 43 | var response = await httpClient.SendAsync(request).ConfigureAwait(false); 44 | return await GetResponse(response); 45 | } 46 | } -------------------------------------------------------------------------------- /.github/workflows/publishNuget.yml: -------------------------------------------------------------------------------- 1 | name: Publish package on NuGet 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | 7 | jobs: 8 | job_1: 9 | name: HttpExtension Build 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Setup .NET 14 | uses: actions/setup-dotnet@v1 15 | with: 16 | dotnet-version: '6.0.x' 17 | 18 | - name: Restore dependencies 19 | run: dotnet restore 20 | working-directory: 'HttpExtension/' 21 | 22 | - name: Build 23 | run: dotnet build . --configuration Release --no-restore 24 | working-directory: 'HttpExtension/' 25 | 26 | job_2: 27 | name: HttpExtension release publish 28 | needs: job_1 29 | runs-on: ubuntu-latest 30 | steps: 31 | - uses: actions/checkout@v2 32 | - name: Setup .NET 33 | uses: actions/setup-dotnet@v1 34 | with: 35 | dotnet-version: '6.0.x' 36 | 37 | - name: Install GitVersion 38 | uses: gittools/actions/gitversion/setup@v0.9.7 39 | with: 40 | versionSpec: '5.x' 41 | 42 | - name: Fetch all repository 43 | run: git fetch --unshallow 44 | 45 | - name: Determine Version 46 | uses: gittools/actions/gitversion/execute@v0.9.7 47 | with: 48 | useConfigFile: true 49 | 50 | - name: Change version on csproj file 51 | run: sed -i -e 's/PackageVersion>[0-9a-z.-]*'$GITVERSION_NUGETVERSION'(.*)<\/PackageVersion>\s*$ 67 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /HttpExtension/HttpPutExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Newtonsoft.Json; 7 | using Polly.Retry; 8 | 9 | public static partial class HttpExtensions 10 | { 11 | public static async Task PutAsync(this HttpClient httpClient, string address, object dto, 12 | string mediaType = "application/json") 13 | { 14 | return await InternalPutAsync(httpClient, address, dto, mediaType); 15 | } 16 | 17 | public static async Task PutAsync(this HttpClient httpClient, string address, 18 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 19 | { 20 | return await policy.ExecuteAsync(async () => 21 | { 22 | return await InternalPutAsync(httpClient, address, dto, mediaType); 23 | }); 24 | } 25 | 26 | public static async Task PutAsync(this HttpClient httpClient, string address, 27 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 28 | { 29 | return await policy.ExecuteAsync(async () => 30 | { 31 | return await InternalPutAsync(httpClient, address, dto, mediaType); 32 | }); 33 | } 34 | 35 | public static async Task> PutAsync(this HttpClient httpClient, string address, 36 | object dto, string mediaType = "application/json") 37 | { 38 | try 39 | { 40 | return await InternalPutAsync(httpClient, address, dto, mediaType); 41 | } 42 | catch (Exception ex) 43 | { 44 | return new HttpExtensionResponse( 45 | HttpStatusCode.InternalServerError, 46 | ex); 47 | } 48 | } 49 | 50 | public static async Task> PutAsync(this HttpClient httpClient, string address, 51 | object dto, AsyncRetryPolicy> policy, string mediaType = "application/json") 52 | { 53 | return await policy.ExecuteAsync(async () => 54 | { 55 | return await InternalPutAsync(httpClient, address, dto, mediaType); 56 | }); 57 | } 58 | 59 | public static async Task> PutAsync(this HttpClient httpClient, string address, 60 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 61 | { 62 | return await policy.ExecuteAsync(async () => 63 | { 64 | return await InternalPutAsync(httpClient, address, dto, mediaType); 65 | }); 66 | } 67 | 68 | private static async Task InternalPutAsync(HttpClient httpClient, string address, object dto, string mediaType) 69 | { 70 | var jsonRequest = JsonConvert.SerializeObject(dto); 71 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 72 | 73 | return await httpClient.PutAsync(address, content); 74 | } 75 | 76 | private static async Task> InternalPutAsync(HttpClient httpClient, string address, object dto, string mediaType) 77 | { 78 | var jsonRequest = JsonConvert.SerializeObject(dto); 79 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 80 | 81 | var response = await httpClient.PutAsync( 82 | address, 83 | content); 84 | 85 | return await GetResponse(response); 86 | } 87 | } -------------------------------------------------------------------------------- /HttpExtension/HttpGetExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Polly.Retry; 8 | 9 | public static partial class HttpExtensions 10 | { 11 | public static async Task> GetAsync(this HttpClient httpClient, string address) 12 | { 13 | try 14 | { 15 | return await InternalGetAsync(httpClient, address); 16 | } 17 | catch (Exception ex) 18 | { 19 | return new HttpExtensionResponse( 20 | HttpStatusCode.InternalServerError, 21 | ex); 22 | } 23 | } 24 | 25 | public static async Task> GetAsync(this HttpClient httpClient, string address, 26 | AsyncRetryPolicy> policy) 27 | { 28 | try 29 | { 30 | return await policy.ExecuteAsync(async () => 31 | { 32 | return await InternalGetAsync(httpClient, address); 33 | }); 34 | } 35 | catch (Exception ex) 36 | { 37 | return new HttpExtensionResponse( 38 | HttpStatusCode.InternalServerError, 39 | ex); 40 | } 41 | } 42 | 43 | public static async Task> GetAsync(this HttpClient httpClient, string address, 44 | AsyncRetryPolicy policy) 45 | { 46 | try 47 | { 48 | return await policy.ExecuteAsync(async () => 49 | { 50 | return await InternalGetAsync(httpClient, address); 51 | }); 52 | } 53 | catch (Exception ex) 54 | { 55 | return new HttpExtensionResponse( 56 | HttpStatusCode.InternalServerError, 57 | ex); 58 | } 59 | } 60 | 61 | public static async Task> GetAsync(this HttpClient httpClient, string address, 62 | Dictionary values) 63 | { 64 | try 65 | { 66 | return await InternalGetAsync(httpClient, address, values); 67 | } 68 | catch (Exception ex) 69 | { 70 | return new HttpExtensionResponse( 71 | HttpStatusCode.InternalServerError, 72 | ex); 73 | } 74 | } 75 | 76 | public static async Task> GetAsync(this HttpClient httpClient, string address, 77 | Dictionary values, AsyncRetryPolicy> policy) 78 | { 79 | try 80 | { 81 | return await policy.ExecuteAsync(async () => 82 | { 83 | return await InternalGetAsync(httpClient, address, values); 84 | }); 85 | } 86 | catch (Exception ex) 87 | { 88 | return new HttpExtensionResponse( 89 | HttpStatusCode.InternalServerError, 90 | ex); 91 | } 92 | } 93 | 94 | public static async Task> GetAsync(this HttpClient httpClient, string address, 95 | Dictionary values, AsyncRetryPolicy policy) 96 | { 97 | try 98 | { 99 | return await policy.ExecuteAsync(async () => 100 | { 101 | return await InternalGetAsync(httpClient, address, values); 102 | }); 103 | } 104 | catch (Exception ex) 105 | { 106 | return new HttpExtensionResponse( 107 | HttpStatusCode.InternalServerError, 108 | ex); 109 | } 110 | } 111 | 112 | private static async Task> InternalGetAsync(HttpClient httpClient, string address) 113 | { 114 | var response = await httpClient.GetAsync(address).ConfigureAwait(false); 115 | return await GetResponse(response); 116 | } 117 | 118 | private static async Task> InternalGetAsync(HttpClient httpClient, string address, 119 | Dictionary values) 120 | { 121 | var builder = new StringBuilder(); 122 | 123 | foreach (var pair in values) 124 | builder.Append($"&{pair.Key}={pair.Value}"); 125 | 126 | var url = $"{address}?{builder.ToString().Substring(1)}"; 127 | var response = await httpClient.GetAsync(url).ConfigureAwait(false); 128 | return await GetResponse(response); 129 | } 130 | } -------------------------------------------------------------------------------- /HttpExtension/HttpDeleteExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Newtonsoft.Json; 7 | using Polly.Retry; 8 | 9 | public static partial class HttpExtensions 10 | { 11 | public static async Task DeleteAsync(this HttpClient httpClient, 12 | string address, object dto, string mediaType = "application/json") 13 | { 14 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 15 | } 16 | 17 | public static async Task DeleteAsync(this HttpClient httpClient, string address, 18 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 19 | { 20 | return await policy.ExecuteAsync(async () => 21 | { 22 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 23 | }); 24 | } 25 | 26 | public static async Task DeleteAsync(this HttpClient httpClient, string address, 27 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 28 | { 29 | return await policy.ExecuteAsync(async () => 30 | { 31 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 32 | }); 33 | } 34 | 35 | public static async Task> DeleteAsync(this HttpClient httpClient, string address, 36 | object dto, string mediaType = "application/json") 37 | { 38 | try 39 | { 40 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 41 | } 42 | catch (Exception ex) 43 | { 44 | return new HttpExtensionResponse( 45 | HttpStatusCode.InternalServerError, 46 | ex); 47 | } 48 | } 49 | 50 | public static async Task> DeleteAsync(this HttpClient httpClient, string address, 51 | object dto, AsyncRetryPolicy> policy, string mediaType = "application/json") 52 | { 53 | return await policy.ExecuteAsync(async () => 54 | { 55 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 56 | }); 57 | } 58 | 59 | public static async Task> DeleteAsync(this HttpClient httpClient, string address, 60 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 61 | { 62 | return await policy.ExecuteAsync(async () => 63 | { 64 | return await InternalDeleteAsync(httpClient, address, dto, mediaType); 65 | }); 66 | } 67 | 68 | public static async Task> DeleteAsync(this HttpClient httpClient, string address) 69 | { 70 | try 71 | { 72 | return await InternalDeleteAsync(httpClient, address); 73 | } 74 | catch (Exception ex) 75 | { 76 | return new HttpExtensionResponse( 77 | HttpStatusCode.InternalServerError, 78 | ex); 79 | } 80 | } 81 | public static async Task> DeleteAsync(this HttpClient httpClient, string address, 82 | AsyncRetryPolicy> policy) 83 | { 84 | return await policy.ExecuteAsync(async () => 85 | { 86 | return await InternalDeleteAsync(httpClient, address); 87 | }); 88 | } 89 | 90 | private static async Task InternalDeleteAsync(HttpClient httpClient, string address, object dto, string mediaType) 91 | { 92 | var jsonRequest = JsonConvert.SerializeObject(dto); 93 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 94 | 95 | return await httpClient.DeleteAsync(address, content); 96 | } 97 | 98 | private static async Task> InternalDeleteAsync(HttpClient httpClient, string address) 99 | { 100 | 101 | var response = await httpClient.DeleteAsync(address); 102 | return await GetResponse(response); 103 | } 104 | 105 | private static async Task> InternalDeleteAsync(HttpClient httpClient, string address, object dto, string mediaType) 106 | { 107 | var jsonRequest = JsonConvert.SerializeObject(dto); 108 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 109 | 110 | var response = await httpClient.DeleteAsync( 111 | address, 112 | content); 113 | 114 | return await GetResponse(response); 115 | } 116 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HttpExtension 2 | 3 | Extensions for HttpClient 4 | 5 | ###### This is the component, works on .NET Core and.NET Framework 6 | 7 | **NuGet** 8 | 9 | |Name|Info|Contributors| 10 | | ------------------- | ------------------- | ------------------- | 11 | |HttpExtension|[![NuGet](https://buildstats.info/nuget/HttpExtension)](https://www.nuget.org/packages/HttpExtension/)|[![GitHub contributors](https://img.shields.io/github/contributors/TBertuzzi/HttpExtension.svg)](https://github.com/TBertuzzi/HttpExtension/graphs/contributors)| 12 | 13 | **Platform Support** 14 | 15 | HttpExtension is a netstandard 2.1 library. 16 | 17 | Extensions to make using HttpClient easy. 18 | 19 | * GetAsync : Gets the return of a Get Rest and converts to the object or collection of pre-defined objects. 20 | You can use only the path of the rest method, or pass a parameter dictionary. In case the url has parameters. 21 | 22 | ```csharp 23 | public static async Task> GetAsync(this HttpClient httpClient, string address); 24 | public static async Task> GetAsync(this HttpClient httpClient, string address, Dictionary values); 25 | ``` 26 | 27 | 28 | * PostAsync,PutAsync and DeleteAsync : Use post, put and delete service methods rest asynchronously and return objects if necessary. 29 | 30 | ```csharp 31 | public static async Task PostAsync(this HttpClient httpClient, string address, object dto); 32 | public static async Task> PostAsync(this HttpClient httpClient, string address, object dto); 33 | 34 | public static async Task PutAsync(this HttpClient httpClient,string address, object dto); 35 | public static async Task> PutAsync(this HttpClient httpClient, string address, object dto); 36 | 37 | public static async Task DeleteAsync(this HttpClient httpClient,string address, object dto); 38 | public static async Task> DeleteAsync(this HttpClient httpClient, string address, object dto); 39 | ``` 40 | 41 | * SendAsync : Use SendAsync for your custom HTTP request message and return predefined objects or collection. 42 | 43 | ```csharp 44 | public static async Task> SendAsync(this HttpClient httpClient, HttpRequestMessage request); 45 | ``` 46 | 47 | * HttpExtensionResponse : Object that facilitates the return of requests Rest. It returns the Http code of the request, already converted object and the contents in case of errors. 48 | 49 | ```csharp 50 | public class HttpExtensionResponse 51 | { 52 | public HttpStatusCode StatusCode { get; private set; } 53 | 54 | public T Value { get; set; } 55 | 56 | public string Content { get; set; } 57 | 58 | public Exception Error { get; set; } 59 | } 60 | ``` 61 | 62 | Example of use : 63 | 64 | ```csharp 65 | public async Task> GetTodos() 66 | { 67 | try 68 | { 69 | //GetAsync Return with Object 70 | var response = await _httpClient.GetAsync>("todos"); 71 | 72 | if (response.StatusCode == HttpStatusCode.OK) 73 | { 74 | return response.Value; 75 | } 76 | else 77 | { 78 | throw new Exception( 79 | $"HttpStatusCode: {response.StatusCode.ToString()} Message: {response.Content}"); 80 | } 81 | } 82 | catch (Exception ex) 83 | { 84 | throw new Exception(ex.Message); 85 | } 86 | } 87 | ``` 88 | 89 | **Retry Pattern support using Polly** 90 | 91 | You can use the retry pattern with HttpExtension using [Polly](https://github.com/App-vNext/Polly). 92 | 93 | Example of use : 94 | 95 | ```csharp 96 | public async Task> GetTodos() 97 | { 98 | var policy = CreatePolicy(); 99 | try 100 | { 101 | //GetAsync using retry pattern 102 | var response = await _httpClient.GetAsync>("todos", policy); 103 | 104 | if (response.StatusCode == HttpStatusCode.OK) 105 | return response.Value; 106 | else 107 | { 108 | throw new Exception( 109 | $"HttpStatusCode: {response.StatusCode.ToString()} Message: {response.Content}"); 110 | } 111 | } 112 | catch (Exception ex) 113 | { 114 | throw new Exception(ex.Message); 115 | } 116 | } 117 | 118 | private AsyncRetryPolicy CreatePolicy() 119 | { 120 | return Policy 121 | .Handle() 122 | .WaitAndRetryAsync( 123 | retryCount: 3, 124 | sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(2) 125 | ); 126 | } 127 | ``` 128 | -------------------------------------------------------------------------------- /HttpExtension/HttpPostExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Newtonsoft.Json; 7 | using Polly.Retry; 8 | 9 | public static partial class HttpExtensions 10 | { 11 | public static async Task PostAsync(this HttpClient httpClient, string address, 12 | object dto, string mediaType = "application/json") 13 | { 14 | return await InternalPostAsync(httpClient, address, dto, mediaType); 15 | } 16 | 17 | public static async Task PostAsync(this HttpClient httpClient, string address, 18 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 19 | { 20 | return await policy.ExecuteAsync(async () => 21 | { 22 | return await InternalPostAsync(httpClient, address, dto, mediaType); 23 | }); 24 | } 25 | 26 | public static async Task PostAsync(this HttpClient httpClient, string address, 27 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 28 | { 29 | return await policy.ExecuteAsync(async () => 30 | { 31 | return await InternalPostAsync(httpClient, address, dto, mediaType); 32 | }); 33 | } 34 | 35 | public static async Task> PostAsync(this HttpClient httpClient, string address) 36 | { 37 | try 38 | { 39 | return await InternalPostAsync(httpClient, address); 40 | } 41 | catch (Exception ex) 42 | { 43 | return new HttpExtensionResponse( 44 | HttpStatusCode.InternalServerError, 45 | ex); 46 | } 47 | } 48 | 49 | public static async Task> PostAsync(this HttpClient httpClient, string address, 50 | AsyncRetryPolicy> policy) 51 | { 52 | return await policy.ExecuteAsync(async () => 53 | { 54 | return await InternalPostAsync(httpClient, address); 55 | }); 56 | } 57 | 58 | public static async Task> PostAsync(this HttpClient httpClient, string address, 59 | AsyncRetryPolicy policy) 60 | { 61 | return await policy.ExecuteAsync(async () => 62 | { 63 | return await InternalPostAsync(httpClient, address); 64 | }); 65 | } 66 | 67 | public static async Task> PostAsync(this HttpClient httpClient, string address, 68 | object dto, string mediaType = "application/json") 69 | { 70 | try 71 | { 72 | return await InternalPostAsync(httpClient, address, dto, mediaType); 73 | } 74 | catch (Exception ex) 75 | { 76 | return new HttpExtensionResponse( 77 | HttpStatusCode.InternalServerError, 78 | ex); 79 | } 80 | } 81 | 82 | public static async Task> PostAsync(this HttpClient httpClient, string address, 83 | object dto, AsyncRetryPolicy> policy, string mediaType = "application/json") 84 | { 85 | return await policy.ExecuteAsync(async () => 86 | { 87 | return await InternalPostAsync(httpClient, address, dto, mediaType); 88 | }); 89 | } 90 | 91 | public static async Task> PostAsync(this HttpClient httpClient, string address, 92 | object dto, AsyncRetryPolicy policy, string mediaType = "application/json") 93 | { 94 | return await policy.ExecuteAsync(async () => 95 | { 96 | return await InternalPostAsync(httpClient, address, dto, mediaType); 97 | }); 98 | } 99 | 100 | private static async Task InternalPostAsync(HttpClient httpClient, string address, object dto, string mediaType) 101 | { 102 | var jsonRequest = JsonConvert.SerializeObject(dto); 103 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 104 | 105 | return await httpClient.PostAsync(address, content); 106 | } 107 | 108 | private static async Task> InternalPostAsync(HttpClient httpClient, string address) 109 | { 110 | var response = await httpClient.PostAsync(address, null); 111 | return await GetResponse(response); 112 | } 113 | 114 | private static async Task> InternalPostAsync(HttpClient httpClient, string address, object dto, string mediaType) 115 | { 116 | var jsonRequest = JsonConvert.SerializeObject(dto); 117 | var content = new StringContent(jsonRequest, Encoding.UTF8, mediaType); 118 | 119 | var response = await httpClient.PostAsync( 120 | address, 121 | content); 122 | 123 | return await GetResponse(response); 124 | } 125 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc --------------------------------------------------------------------------------