├── .gitattributes ├── .gitignore ├── CONTRIBUTING.md ├── HttpClient.sln ├── LICENSE.txt ├── NuGet.Config ├── README.md ├── build.cmd ├── build.sh ├── global.json ├── makefile.shade ├── samples └── TestClient │ ├── App.config │ ├── Program.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── TestClient.csproj │ ├── TestClient.kproj │ └── project.json ├── src └── Microsoft.Net.Http.Client │ ├── ApmStream.cs │ ├── ApmStreamWrapper.cs │ ├── BufferedReadStream.cs │ ├── ChunkedReadStream.cs │ ├── ContentLengthReadStream.cs │ ├── HttpConnection.cs │ ├── HttpConnectionResponseContent.cs │ ├── ManagedHandler.cs │ ├── Microsoft.Net.Http.Client.csproj │ ├── Microsoft.Net.Http.Client.kproj │ ├── Properties │ └── AssemblyInfo.cs │ ├── ProxyMode.cs │ ├── RedirectMode.cs │ ├── RequestExtensions.cs │ └── project.json └── test └── Microsoft.Net.Http.Client.FunctionalTests ├── HelloWorldTests.cs ├── Microsoft.Net.Http.Client.FunctionalTests.csproj ├── Microsoft.Net.Http.Client.FunctionalTests.kproj ├── Properties └── AssemblyInfo.cs ├── RedirectTests.cs ├── Utilities.cs ├── packages.config └── project.json /.gitattributes: -------------------------------------------------------------------------------- 1 | *.doc diff=astextplain 2 | *.DOC diff=astextplain 3 | *.docx diff=astextplain 4 | *.DOCX diff=astextplain 5 | *.dot diff=astextplain 6 | *.DOT diff=astextplain 7 | *.pdf diff=astextplain 8 | *.PDF diff=astextplain 9 | *.rtf diff=astextplain 10 | *.RTF diff=astextplain 11 | 12 | *.jpg binary 13 | *.png binary 14 | *.gif binary 15 | 16 | *.cs text=auto diff=csharp 17 | *.vb text=auto 18 | *.resx text=auto 19 | *.c text=auto 20 | *.cpp text=auto 21 | *.cxx text=auto 22 | *.h text=auto 23 | *.hxx text=auto 24 | *.py text=auto 25 | *.rb text=auto 26 | *.java text=auto 27 | *.html text=auto 28 | *.htm text=auto 29 | *.css text=auto 30 | *.scss text=auto 31 | *.sass text=auto 32 | *.less text=auto 33 | *.js text=auto 34 | *.lisp text=auto 35 | *.clj text=auto 36 | *.sql text=auto 37 | *.php text=auto 38 | *.lua text=auto 39 | *.m text=auto 40 | *.asm text=auto 41 | *.erl text=auto 42 | *.fs text=auto 43 | *.fsx text=auto 44 | *.hs text=auto 45 | 46 | *.csproj text=auto 47 | *.vbproj text=auto 48 | *.fsproj text=auto 49 | *.dbproj text=auto 50 | *.sln text=auto eol=crlf 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | [Oo]bj/ 2 | [Bb]in/ 3 | TestResults/ 4 | .nuget/ 5 | *.sln.ide/ 6 | _ReSharper.*/ 7 | packages/ 8 | artifacts/ 9 | PublishProfiles/ 10 | *.user 11 | *.suo 12 | *.cache 13 | *.docstates 14 | _ReSharper.* 15 | nuget.exe 16 | *net45.csproj 17 | *net451.csproj 18 | *k10.csproj 19 | *.psess 20 | *.vsp 21 | *.pidb 22 | *.userprefs 23 | *DS_Store 24 | *.ncrunchsolution 25 | *.*sdf 26 | *.ipch -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ====== 3 | 4 | Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/master/CONTRIBUTING.md) in the Home repo. 5 | -------------------------------------------------------------------------------- /HttpClient.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.22228.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.Net.Http.Client", "src\Microsoft.Net.Http.Client\Microsoft.Net.Http.Client.kproj", "{9057D304-79FB-4B91-8C28-B7AB22ED20FE}" 7 | EndProject 8 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Microsoft.Net.Http.Client.FunctionalTests", "test\Microsoft.Net.Http.Client.FunctionalTests\Microsoft.Net.Http.Client.FunctionalTests.kproj", "{010C9E4F-A496-43B7-BFFC-5E6E2F64552E}" 9 | EndProject 10 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestClient", "samples\TestClient\TestClient.kproj", "{9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{B0A0E824-39C6-469D-9E28-C8731D5DF69E}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{330EDBBD-F18B-4136-A492-30AFC06BB68B}" 15 | ProjectSection(SolutionItems) = preProject 16 | global.json = global.json 17 | EndProjectSection 18 | EndProject 19 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{34DC8DD8-7C39-415D-98E9-E11F12FD735F}" 20 | EndProject 21 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{44812035-7134-4877-BD8C-F011171FF21D}" 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {9057D304-79FB-4B91-8C28-B7AB22ED20FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {9057D304-79FB-4B91-8C28-B7AB22ED20FE}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {9057D304-79FB-4B91-8C28-B7AB22ED20FE}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {9057D304-79FB-4B91-8C28-B7AB22ED20FE}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {010C9E4F-A496-43B7-BFFC-5E6E2F64552E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {010C9E4F-A496-43B7-BFFC-5E6E2F64552E}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {010C9E4F-A496-43B7-BFFC-5E6E2F64552E}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {010C9E4F-A496-43B7-BFFC-5E6E2F64552E}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(NestedProjects) = preSolution 46 | {9057D304-79FB-4B91-8C28-B7AB22ED20FE} = {B0A0E824-39C6-469D-9E28-C8731D5DF69E} 47 | {010C9E4F-A496-43B7-BFFC-5E6E2F64552E} = {44812035-7134-4877-BD8C-F011171FF21D} 48 | {9BC253B1-FEB5-4475-ACA6-EAECB4FBFE32} = {34DC8DD8-7C39-415D-98E9-E11F12FD735F} 49 | EndGlobalSection 50 | EndGlobal 51 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | these files except in compliance with the License. You may obtain a copy of the 5 | License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software distributed 10 | under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 11 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 12 | specific language governing permissions and limitations under the License. 13 | -------------------------------------------------------------------------------- /NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | HttpClient 2 | === 3 | 4 | Fully managed HttpMessageHandler implementation based on sockets. 5 | 6 | 7 | This project is part of ASP.NET vNext. You can find samples, documentation and getting started instructions for ASP.NET vNext at the [Home](https://github.com/aspnet/home) repo. 8 | 9 | -------------------------------------------------------------------------------- /build.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | cd %~dp0 3 | 4 | SETLOCAL 5 | SET CACHED_NUGET=%LocalAppData%\NuGet\NuGet.exe 6 | 7 | IF EXIST %CACHED_NUGET% goto copynuget 8 | echo Downloading latest version of NuGet.exe... 9 | IF NOT EXIST %LocalAppData%\NuGet md %LocalAppData%\NuGet 10 | @powershell -NoProfile -ExecutionPolicy unrestricted -Command "$ProgressPreference = 'SilentlyContinue'; Invoke-WebRequest 'https://www.nuget.org/nuget.exe' -OutFile '%CACHED_NUGET%'" 11 | 12 | :copynuget 13 | IF EXIST .nuget\nuget.exe goto restore 14 | md .nuget 15 | copy %CACHED_NUGET% .nuget\nuget.exe > nul 16 | 17 | :restore 18 | IF EXIST packages\KoreBuild goto run 19 | .nuget\NuGet.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre 20 | .nuget\NuGet.exe install Sake -version 0.2 -o packages -ExcludeVersion 21 | 22 | IF "%SKIP_KRE_INSTALL%"=="1" goto run 23 | CALL packages\KoreBuild\build\kvm upgrade -runtime CLR -x86 24 | CALL packages\KoreBuild\build\kvm install default -runtime CoreCLR -x86 25 | 26 | :run 27 | CALL packages\KoreBuild\build\kvm use default -runtime CLR -x86 28 | packages\Sake\tools\Sake.exe -I packages\KoreBuild\build -f makefile.shade %* 29 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | if test `uname` = Darwin; then 4 | cachedir=~/Library/Caches/KBuild 5 | else 6 | if x$XDG_DATA_HOME = x; then 7 | cachedir=$HOME/.local/share 8 | else 9 | cachedir=$XDG_DATA_HOME; 10 | fi 11 | fi 12 | mkdir -p $cachedir 13 | 14 | url=https://www.nuget.org/nuget.exe 15 | 16 | if test ! -f $cachedir/nuget.exe; then 17 | wget -o $cachedir/nuget.exe $url 2>/dev/null || curl -o $cachedir/nuget.exe --location $url /dev/null 18 | fi 19 | 20 | if test ! -e .nuget; then 21 | mkdir .nuget 22 | cp $cachedir/nuget.exe .nuget 23 | fi 24 | 25 | if test ! -d packages/KoreBuild; then 26 | mono .nuget/nuget.exe install KoreBuild -ExcludeVersion -o packages -nocache -pre 27 | mono .nuget/nuget.exe install Sake -version 0.2 -o packages -ExcludeVersion 28 | fi 29 | 30 | KRE_VERSION=$(mono .nuget/nuget.exe install KRE-mono45-x86 -pre -o ~/.kre/packages | head -1 | sed "s/.*KRE-mono45-x86 \([^']*\).*/\1/") 31 | KRE_BIN=~/.kre/packages/KRE-mono45-x86.$KRE_VERSION/bin 32 | 33 | chmod +x $KRE_BIN/k 34 | chmod +x $KRE_BIN/klr 35 | chmod +x $KRE_BIN/kpm 36 | chmod +x $KRE_BIN/k-build 37 | 38 | export PATH=$KRE_BIN:$PATH 39 | 40 | mono packages/Sake/tools/Sake.exe -I packages/KoreBuild/build -f makefile.shade "$@" -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sources": ["src"] 3 | } -------------------------------------------------------------------------------- /makefile.shade: -------------------------------------------------------------------------------- 1 | 2 | var VERSION='1.0' 3 | var FULL_VERSION='0.1' 4 | var AUTHORS='Microsoft' 5 | 6 | use-standard-lifecycle 7 | k-standard-goals 8 | -------------------------------------------------------------------------------- /samples/TestClient/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /samples/TestClient/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using Microsoft.Net.Http.Client; 4 | 5 | namespace TestClient 6 | { 7 | class Program 8 | { 9 | public static void Main(string[] args) 10 | { 11 | // System.Diagnostics.Debugger.Launch(); 12 | HttpClient client = new HttpClient(new ManagedHandler() 13 | { 14 | // ProxyAddress = new Uri("http://itgproxy:80") 15 | }); 16 | 17 | var response = client.GetAsync( 18 | // "https://www.myget.org/f/aspnetwebstacknightly/" 19 | "https://packages.nuget.org/v1/Package/Download/EntityFramework/4.1.10331.0" 20 | ).Result; 21 | Console.WriteLine(response); 22 | // Console.WriteLine(response.Content.ReadAsStringAsync().Result); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /samples/TestClient/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TestClient")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TestClient")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("dc4c9e7d-020e-4031-9e7d-3dcfb042f2b8")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /samples/TestClient/TestClient.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {66DB9DF3-F8EF-4447-B0A6-C3512D73544E} 8 | Exe 9 | Properties 10 | TestClient 11 | TestClient 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 59 | -------------------------------------------------------------------------------- /samples/TestClient/TestClient.kproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 12.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 9bc253b1-feb5-4475-aca6-eaecb4fbfe32 10 | Library 11 | 12 | 13 | ConsoleDebugger 14 | 15 | 16 | WebDebugger 17 | 18 | 19 | 20 | 21 | 22 | 23 | TestClient 24 | 25 | 26 | TestClient 27 | 28 | 29 | 2.0 30 | 31 | 32 | -------------------------------------------------------------------------------- /samples/TestClient/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "Microsoft.Net.Http.Client": "1.0.0-*" 4 | }, 5 | "frameworks": { 6 | "net45": { 7 | "frameworkAssemblies": { 8 | "System.Net.Http": "" 9 | } 10 | }, 11 | "aspnet50": { 12 | "frameworkAssemblies": { 13 | "System.Net.Http": "" 14 | } 15 | }, 16 | "aspnetcore50": { 17 | "dependencies": { 18 | "System.Console": "4.0.0-beta-*", 19 | "System.Net.Http": "4.0.0-beta-*", 20 | "System.Runtime": "4.0.20-beta-*" 21 | } 22 | } 23 | }, 24 | "webroot": null 25 | } -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ApmStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace Microsoft.Net.Http.Client 5 | { 6 | /// 7 | /// Summary description for ApmStream 8 | /// 9 | public abstract class ApmStream : Stream 10 | { 11 | #if !NET45 12 | public abstract IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state); 13 | #endif 14 | 15 | #if !NET45 16 | public abstract int EndRead(IAsyncResult asyncResult); 17 | #endif 18 | 19 | #if !NET45 20 | public abstract IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state); 21 | #endif 22 | 23 | #if !NET45 24 | public abstract void EndWrite(IAsyncResult asyncResult); 25 | #endif 26 | } 27 | } -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ApmStreamWrapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | 6 | namespace Microsoft.Net.Http.Client 7 | { 8 | public class ApmStreamWrapper : ApmStream 9 | { 10 | private Stream _innerStream; 11 | 12 | public ApmStreamWrapper(Stream innerStream) 13 | { 14 | _innerStream = innerStream; 15 | } 16 | 17 | public override bool CanRead 18 | { 19 | get 20 | { 21 | return _innerStream.CanRead; 22 | } 23 | } 24 | 25 | public override bool CanSeek 26 | { 27 | get 28 | { 29 | return _innerStream.CanSeek; 30 | } 31 | } 32 | 33 | public override bool CanWrite 34 | { 35 | get 36 | { 37 | return _innerStream.CanWrite; 38 | } 39 | } 40 | 41 | public override bool CanTimeout 42 | { 43 | get 44 | { 45 | return _innerStream.CanTimeout; 46 | } 47 | } 48 | 49 | public override int ReadTimeout 50 | { 51 | get 52 | { 53 | return _innerStream.ReadTimeout; 54 | } 55 | 56 | set 57 | { 58 | _innerStream.ReadTimeout = value; 59 | } 60 | } 61 | 62 | public override int WriteTimeout 63 | { 64 | get 65 | { 66 | return _innerStream.WriteTimeout; 67 | } 68 | 69 | set 70 | { 71 | _innerStream.WriteTimeout = value; 72 | } 73 | } 74 | 75 | public override long Length 76 | { 77 | get 78 | { 79 | return _innerStream.Length; 80 | } 81 | } 82 | 83 | public override long Position 84 | { 85 | get 86 | { 87 | return _innerStream.Position; 88 | } 89 | 90 | set 91 | { 92 | _innerStream.Position = value; 93 | } 94 | } 95 | 96 | public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) 97 | { 98 | #if ASPNETCORE50 99 | TaskCompletionSource tcs = new TaskCompletionSource(state); 100 | InternalReadAsync(buffer, offset, size, callback, tcs); 101 | return tcs.Task; 102 | #else 103 | return _innerStream.BeginRead(buffer, offset, size, callback, state); 104 | #endif 105 | } 106 | 107 | #if ASPNETCORE50 108 | private async void InternalReadAsync(byte[] buffer, int offset, int size, AsyncCallback callback, TaskCompletionSource tcs) 109 | { 110 | try 111 | { 112 | int read = await _innerStream.ReadAsync(buffer, offset, size); 113 | tcs.TrySetResult(read); 114 | } 115 | catch (Exception ex) 116 | { 117 | tcs.TrySetException(ex); 118 | } 119 | 120 | try 121 | { 122 | callback(tcs.Task); 123 | } 124 | catch (Exception) 125 | { 126 | } 127 | } 128 | #endif 129 | 130 | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) 131 | { 132 | #if ASPNETCORE50 133 | TaskCompletionSource tcs = new TaskCompletionSource(state); 134 | InternalWriteAsync(buffer, offset, size, callback, tcs); 135 | return tcs.Task; 136 | #else 137 | return _innerStream.BeginWrite(buffer, offset, size, callback, state); 138 | #endif 139 | } 140 | 141 | #if ASPNETCORE50 142 | private async void InternalWriteAsync(byte[] buffer, int offset, int size, AsyncCallback callback, TaskCompletionSource tcs) 143 | { 144 | try 145 | { 146 | await _innerStream.WriteAsync(buffer, offset, size); 147 | tcs.TrySetResult(null); 148 | } 149 | catch (Exception ex) 150 | { 151 | tcs.TrySetException(ex); 152 | } 153 | 154 | try 155 | { 156 | callback(tcs.Task); 157 | } 158 | catch (Exception) 159 | { 160 | } 161 | } 162 | #endif 163 | 164 | public override int EndRead(IAsyncResult asyncResult) 165 | { 166 | #if ASPNETCORE50 167 | Task t = (Task)asyncResult; 168 | t.Wait(); 169 | 170 | if (t.IsFaulted) 171 | { 172 | throw new IOException(string.Empty, t.Exception); 173 | } 174 | return t.Result; 175 | #else 176 | return _innerStream.EndRead(asyncResult); 177 | #endif 178 | } 179 | 180 | public override void EndWrite(IAsyncResult asyncResult) 181 | { 182 | #if ASPNETCORE50 183 | Task t = (Task)asyncResult; 184 | t.Wait(); 185 | 186 | if (t.IsFaulted) 187 | { 188 | throw new IOException(string.Empty, t.Exception); 189 | } 190 | #else 191 | _innerStream.EndWrite(asyncResult); 192 | #endif 193 | } 194 | 195 | public override void Flush() 196 | { 197 | _innerStream.Flush(); 198 | } 199 | 200 | public override int Read(byte[] buffer, int offset, int count) 201 | { 202 | return _innerStream.Read(buffer, offset, count); 203 | } 204 | 205 | public override long Seek(long offset, SeekOrigin origin) 206 | { 207 | return _innerStream.Seek(offset, origin); 208 | } 209 | 210 | public override void SetLength(long value) 211 | { 212 | SetLength(value); 213 | } 214 | 215 | public override void Write(byte[] buffer, int offset, int count) 216 | { 217 | _innerStream.Write(buffer, offset, count); 218 | } 219 | 220 | protected override void Dispose(bool disposing) 221 | { 222 | if (disposing) 223 | { 224 | _innerStream.Dispose(); 225 | } 226 | } 227 | 228 | public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) 229 | { 230 | return _innerStream.CopyToAsync(destination, bufferSize, cancellationToken); 231 | } 232 | 233 | public override Task FlushAsync(CancellationToken cancellationToken) 234 | { 235 | return _innerStream.FlushAsync(cancellationToken); 236 | } 237 | 238 | public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 239 | { 240 | return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); 241 | } 242 | 243 | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 244 | { 245 | return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); 246 | } 247 | 248 | public override int ReadByte() 249 | { 250 | return _innerStream.ReadByte(); 251 | } 252 | 253 | public override void WriteByte(byte value) 254 | { 255 | _innerStream.WriteByte(value); 256 | } 257 | } 258 | } 259 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/BufferedReadStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Text; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace Microsoft.Net.Http.Client 8 | { 9 | public class BufferedReadStream : ApmStream 10 | { 11 | private const char CR = '\r'; 12 | private const char LF = '\n'; 13 | 14 | private readonly ApmStream _inner; 15 | private readonly byte[] _buffer; 16 | private int _bufferOffset = 0; 17 | private int _bufferCount = 0; 18 | private bool _disposed; 19 | 20 | public BufferedReadStream(ApmStream inner) 21 | { 22 | if (inner == null) 23 | { 24 | throw new ArgumentNullException("inner"); 25 | } 26 | _inner = inner; 27 | _buffer = new byte[1024]; 28 | } 29 | 30 | public override bool CanRead 31 | { 32 | get { return _inner.CanRead || _bufferCount > 0; } 33 | } 34 | 35 | public override bool CanSeek 36 | { 37 | get { return false; } 38 | } 39 | 40 | public override bool CanTimeout 41 | { 42 | get { return _inner.CanTimeout; } 43 | } 44 | 45 | public override bool CanWrite 46 | { 47 | get { return _inner.CanWrite; } 48 | } 49 | 50 | public override long Length 51 | { 52 | get { throw new NotSupportedException(); } 53 | } 54 | 55 | public override long Position 56 | { 57 | get { throw new NotSupportedException(); } 58 | set { throw new NotSupportedException(); } 59 | } 60 | 61 | public override long Seek(long offset, SeekOrigin origin) 62 | { 63 | throw new NotSupportedException(); 64 | } 65 | 66 | public override void SetLength(long value) 67 | { 68 | throw new NotSupportedException(); 69 | } 70 | 71 | protected override void Dispose(bool disposing) 72 | { 73 | _disposed = true; 74 | if (disposing) 75 | { 76 | _inner.Dispose(); 77 | } 78 | } 79 | 80 | public override void Flush() 81 | { 82 | _inner.Flush(); 83 | } 84 | 85 | public override Task FlushAsync(CancellationToken cancellationToken) 86 | { 87 | return _inner.FlushAsync(cancellationToken); 88 | } 89 | 90 | public override void Write(byte[] buffer, int offset, int count) 91 | { 92 | _inner.Write(buffer, offset, count); 93 | } 94 | 95 | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 96 | { 97 | return _inner.BeginWrite(buffer, offset, count, callback, state); 98 | } 99 | 100 | public override void EndWrite(IAsyncResult asyncResult) 101 | { 102 | _inner.EndWrite(asyncResult); 103 | } 104 | 105 | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 106 | { 107 | return _inner.WriteAsync(buffer, offset, count, cancellationToken); 108 | } 109 | 110 | public override int Read(byte[] buffer, int offset, int count) 111 | { 112 | // Validate Inputs 113 | 114 | // Drain buffer 115 | if (_bufferCount > 0) 116 | { 117 | int toCopy = Math.Min(_bufferCount, count); 118 | Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy); 119 | _bufferOffset += toCopy; 120 | _bufferCount -= toCopy; 121 | return toCopy; 122 | } 123 | 124 | return _inner.Read(buffer, offset, count); 125 | } 126 | 127 | public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 128 | { 129 | // Validate Inputs 130 | 131 | // Drain buffer 132 | if (_bufferCount > 0) 133 | { 134 | int toCopy = Math.Min(_bufferCount, count); 135 | Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy); 136 | _bufferOffset += toCopy; 137 | _bufferCount -= toCopy; 138 | return toCopy; 139 | } 140 | 141 | return await _inner.ReadAsync(buffer, offset, count, cancellationToken); 142 | } 143 | 144 | // We only anticipate using ReadAsync 145 | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 146 | { 147 | // Validate Inputs 148 | 149 | // Drain buffer 150 | if (_bufferCount > 0) 151 | { 152 | int toCopy = Math.Min(_bufferCount, count); 153 | Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy); 154 | _bufferOffset += toCopy; 155 | _bufferCount -= toCopy; 156 | 157 | TaskCompletionSource tcs = new TaskCompletionSource(state); 158 | tcs.TrySetResult(toCopy); 159 | callback(tcs.Task); 160 | return tcs.Task; 161 | } 162 | 163 | return _inner.BeginRead(buffer, offset, count, callback, state); 164 | } 165 | 166 | public override int EndRead(IAsyncResult asyncResult) 167 | { 168 | Task task = asyncResult as Task; 169 | if (task != null) 170 | { 171 | return task.Result; 172 | } 173 | return _inner.EndRead(asyncResult); 174 | } 175 | 176 | private void EnsureBufferd() 177 | { 178 | if (_bufferCount == 0) 179 | { 180 | _bufferOffset = 0; 181 | _bufferCount = _inner.Read(_buffer, _bufferOffset, _buffer.Length); 182 | if (_bufferCount == 0) 183 | { 184 | throw new IOException("Unexpected end of stream"); 185 | } 186 | } 187 | } 188 | 189 | private async Task EnsureBufferdAsync(CancellationToken cancel) 190 | { 191 | if (_bufferCount == 0) 192 | { 193 | _bufferOffset = 0; 194 | _bufferCount = await _inner.ReadAsync(_buffer, _bufferOffset, _buffer.Length, cancel); 195 | if (_bufferCount == 0) 196 | { 197 | throw new IOException("Unexpected end of stream"); 198 | } 199 | } 200 | } 201 | 202 | // TODO: Line length limits? 203 | public string ReadLine() 204 | { 205 | CheckDisposed(); 206 | StringBuilder builder = new StringBuilder(); 207 | bool foundCR = false, foundCRLF = false; 208 | do 209 | { 210 | if (_bufferCount == 0) 211 | { 212 | EnsureBufferd(); 213 | } 214 | char ch = (char)_buffer[_bufferOffset]; // TODO: Encoding enforcement 215 | builder.Append(ch); 216 | _bufferOffset++; 217 | _bufferCount--; 218 | if (ch == CR) 219 | { 220 | foundCR = true; 221 | } 222 | else if (ch == LF) 223 | { 224 | if (foundCR) 225 | { 226 | foundCRLF = true; 227 | } 228 | else 229 | { 230 | foundCR = false; 231 | } 232 | } 233 | } 234 | while (!foundCRLF); 235 | 236 | return builder.ToString(0, builder.Length - 2); // Drop the CRLF 237 | } 238 | 239 | // TODO: Line length limits? 240 | public async Task ReadLineAsync(CancellationToken cancel) 241 | { 242 | CheckDisposed(); 243 | StringBuilder builder = new StringBuilder(); 244 | bool foundCR = false, foundCRLF = false; 245 | do 246 | { 247 | if (_bufferCount == 0) 248 | { 249 | await EnsureBufferdAsync(cancel); 250 | } 251 | char ch = (char)_buffer[_bufferOffset]; // TODO: Encoding enforcement 252 | builder.Append(ch); 253 | _bufferOffset++; 254 | _bufferCount--; 255 | if (ch == CR) 256 | { 257 | foundCR = true; 258 | } 259 | else if (ch == LF) 260 | { 261 | if (foundCR) 262 | { 263 | foundCRLF = true; 264 | } 265 | else 266 | { 267 | foundCR = false; 268 | } 269 | } 270 | } 271 | while (!foundCRLF); 272 | 273 | return builder.ToString(0, builder.Length - 2); // Drop the CRLF 274 | } 275 | 276 | private void CheckDisposed() 277 | { 278 | if (_disposed) 279 | { 280 | throw new ObjectDisposedException(typeof(BufferedReadStream).FullName); 281 | } 282 | } 283 | } 284 | } 285 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ChunkedReadStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace Microsoft.Net.Http.Client 11 | { 12 | public class ChunkedReadStream : ApmStream 13 | { 14 | private readonly BufferedReadStream _inner; 15 | private bool _expectChunkHeader = true; 16 | private long _chunkBytesRemaining; 17 | private bool _disposed; 18 | 19 | public ChunkedReadStream(BufferedReadStream inner) 20 | { 21 | _inner = inner; 22 | } 23 | 24 | public override bool CanRead 25 | { 26 | get { return !_disposed; } 27 | } 28 | 29 | public override bool CanSeek 30 | { 31 | get { return false; } 32 | } 33 | 34 | public override bool CanTimeout 35 | { 36 | get { return _inner.CanTimeout; } 37 | } 38 | 39 | public override bool CanWrite 40 | { 41 | get { return false; } 42 | } 43 | 44 | public override long Length 45 | { 46 | get { throw new NotSupportedException(); } 47 | } 48 | 49 | public override long Position 50 | { 51 | get { throw new NotSupportedException(); } 52 | set { throw new NotSupportedException(); } 53 | } 54 | 55 | public override int ReadTimeout 56 | { 57 | get 58 | { 59 | CheckDisposed(); 60 | return _inner.ReadTimeout; 61 | } 62 | set 63 | { 64 | CheckDisposed(); 65 | _inner.ReadTimeout = value; 66 | } 67 | } 68 | 69 | public override int WriteTimeout 70 | { 71 | get 72 | { 73 | CheckDisposed(); 74 | return _inner.WriteTimeout; 75 | } 76 | set 77 | { 78 | CheckDisposed(); 79 | _inner.WriteTimeout = value; 80 | } 81 | } 82 | 83 | public override int Read(byte[] buffer, int offset, int count) 84 | { 85 | // TODO: Validate buffer 86 | if (_disposed) 87 | { 88 | return 0; 89 | } 90 | 91 | try 92 | { 93 | if (_expectChunkHeader) 94 | { 95 | System.Diagnostics.Debug.Assert(_chunkBytesRemaining == 0); 96 | string headerLine = _inner.ReadLine(); 97 | if (!long.TryParse(headerLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _chunkBytesRemaining)) 98 | { 99 | throw new IOException("Invalid chunk header: " + headerLine); 100 | } 101 | _expectChunkHeader = false; 102 | } 103 | 104 | int read = 0; 105 | if (_chunkBytesRemaining > 0) 106 | { 107 | // Not the last (empty) chunk. 108 | int toRead = (int)Math.Min(count, _chunkBytesRemaining); 109 | read = _inner.Read(buffer, offset, toRead); 110 | 111 | _chunkBytesRemaining -= read; 112 | System.Diagnostics.Debug.Assert(_chunkBytesRemaining >= 0, "Negative bytes remaining? " + _chunkBytesRemaining); 113 | } 114 | // TODO: else, drain trailer headers. 115 | 116 | if (_chunkBytesRemaining == 0) 117 | { 118 | // End of chunk, read the terminator CRLF 119 | string trailerLine = _inner.ReadLine(); 120 | System.Diagnostics.Debug.Assert(string.IsNullOrEmpty(trailerLine)); 121 | _expectChunkHeader = true; 122 | } 123 | 124 | if (read == 0) 125 | { 126 | Dispose(); 127 | } 128 | return read; 129 | } 130 | catch (Exception) 131 | { 132 | Dispose(); 133 | throw; 134 | } 135 | } 136 | 137 | public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 138 | { 139 | // TODO: Validate buffer 140 | if (_disposed) 141 | { 142 | return 0; 143 | } 144 | 145 | try 146 | { 147 | cancellationToken.ThrowIfCancellationRequested(); 148 | 149 | if (_expectChunkHeader) 150 | { 151 | System.Diagnostics.Debug.Assert(_chunkBytesRemaining == 0); 152 | string headerLine = await _inner.ReadLineAsync(cancellationToken); 153 | if (!long.TryParse(headerLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _chunkBytesRemaining)) 154 | { 155 | throw new IOException("Invalid chunk header: " + headerLine); 156 | } 157 | _expectChunkHeader = false; 158 | } 159 | 160 | int read = 0; 161 | if (_chunkBytesRemaining > 0) 162 | { 163 | // Not the last (empty) chunk. 164 | int toRead = (int)Math.Min(count, _chunkBytesRemaining); 165 | read = await _inner.ReadAsync(buffer, offset, toRead, cancellationToken); 166 | 167 | _chunkBytesRemaining -= read; 168 | System.Diagnostics.Debug.Assert(_chunkBytesRemaining >= 0, "Negative bytes remaining? " + _chunkBytesRemaining); 169 | } 170 | // TODO: else, drain trailer headers. 171 | 172 | if (_chunkBytesRemaining == 0) 173 | { 174 | // End of chunk, read the terminator CRLF 175 | string trailerLine = await _inner.ReadLineAsync(cancellationToken); 176 | System.Diagnostics.Debug.Assert(string.IsNullOrEmpty(trailerLine)); 177 | _expectChunkHeader = true; 178 | } 179 | 180 | if (read == 0) 181 | { 182 | Dispose(); 183 | } 184 | return read; 185 | } 186 | catch (Exception) 187 | { 188 | Dispose(); 189 | throw; 190 | } 191 | } 192 | 193 | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 194 | { 195 | TaskCompletionSource tcs = new TaskCompletionSource(state); 196 | InternalReadAsync(buffer, offset, count, callback, tcs); 197 | return tcs.Task; 198 | } 199 | private async void InternalReadAsync(byte[] buffer, int offset, int count, AsyncCallback callback, TaskCompletionSource tcs) 200 | { 201 | try 202 | { 203 | int read = await ReadAsync(buffer, offset, count); 204 | tcs.TrySetResult(read); 205 | } 206 | catch (Exception ex) 207 | { 208 | tcs.TrySetException(ex); 209 | } 210 | 211 | try 212 | { 213 | callback(tcs.Task); 214 | } 215 | catch (Exception) 216 | { 217 | } 218 | } 219 | 220 | public override int EndRead(IAsyncResult asyncResult) 221 | { 222 | Task t = (Task)asyncResult; 223 | t.Wait(); 224 | 225 | if (t.IsFaulted) 226 | { 227 | throw new IOException(string.Empty, t.Exception); 228 | } 229 | return t.Result; 230 | } 231 | 232 | protected override void Dispose(bool disposing) 233 | { 234 | if (disposing) 235 | { 236 | // TODO: Sync drain with timeout if small number of bytes remaining? This will let us re-use the connection. 237 | _inner.Dispose(); 238 | } 239 | _disposed = true; 240 | } 241 | 242 | private void CheckDisposed() 243 | { 244 | if (_disposed) 245 | { 246 | throw new ObjectDisposedException(typeof(ContentLengthReadStream).FullName); 247 | } 248 | } 249 | 250 | public override void Write(byte[] buffer, int offset, int count) 251 | { 252 | throw new NotSupportedException(); 253 | } 254 | 255 | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 256 | { 257 | throw new NotSupportedException(); 258 | } 259 | 260 | public override void EndWrite(IAsyncResult asyncResult) 261 | { 262 | throw new NotSupportedException(); 263 | } 264 | 265 | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 266 | { 267 | throw new NotSupportedException(); 268 | } 269 | 270 | public override long Seek(long offset, SeekOrigin origin) 271 | { 272 | throw new NotSupportedException(); 273 | } 274 | 275 | public override void SetLength(long value) 276 | { 277 | throw new NotSupportedException(); 278 | } 279 | 280 | public override void Flush() 281 | { 282 | throw new NotSupportedException(); 283 | } 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ContentLengthReadStream.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | 9 | namespace Microsoft.Net.Http.Client 10 | { 11 | public class ContentLengthReadStream : ApmStream 12 | { 13 | private readonly Stream _inner; 14 | private long _bytesRemaining; 15 | private bool _disposed; 16 | 17 | public ContentLengthReadStream(ApmStream inner, long contentLength) 18 | { 19 | _inner = inner; 20 | _bytesRemaining = contentLength; 21 | } 22 | 23 | public override bool CanRead 24 | { 25 | get { return !_disposed; } 26 | } 27 | 28 | public override bool CanSeek 29 | { 30 | get { return false; } 31 | } 32 | 33 | public override bool CanTimeout 34 | { 35 | get { return _inner.CanTimeout; } 36 | } 37 | 38 | public override bool CanWrite 39 | { 40 | get { return false; } 41 | } 42 | 43 | public override long Length 44 | { 45 | get { throw new NotSupportedException(); } 46 | } 47 | 48 | public override long Position 49 | { 50 | get { throw new NotSupportedException(); } 51 | set { throw new NotSupportedException(); } 52 | } 53 | 54 | public override int ReadTimeout 55 | { 56 | get 57 | { 58 | CheckDisposed(); 59 | return _inner.ReadTimeout; 60 | } 61 | set 62 | { 63 | CheckDisposed(); 64 | _inner.ReadTimeout = value; 65 | } 66 | } 67 | 68 | public override int WriteTimeout 69 | { 70 | get 71 | { 72 | CheckDisposed(); 73 | return _inner.WriteTimeout; 74 | } 75 | set 76 | { 77 | CheckDisposed(); 78 | _inner.WriteTimeout = value; 79 | } 80 | } 81 | 82 | private void UpdateBytesRemaining(int read) 83 | { 84 | _bytesRemaining -= read; 85 | if (_bytesRemaining <= 0) 86 | { 87 | _disposed = true; 88 | } 89 | System.Diagnostics.Debug.Assert(_bytesRemaining >= 0, "Negative bytes remaining? " + _bytesRemaining); 90 | } 91 | 92 | public override int Read(byte[] buffer, int offset, int count) 93 | { 94 | // TODO: Validate buffer 95 | if (_disposed) 96 | { 97 | return 0; 98 | } 99 | int toRead = (int)Math.Min(count, _bytesRemaining); 100 | int read = _inner.Read(buffer, offset, toRead); 101 | UpdateBytesRemaining(read); 102 | return read; 103 | } 104 | 105 | public async override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 106 | { 107 | // TODO: Validate args 108 | if (_disposed) 109 | { 110 | return 0; 111 | } 112 | cancellationToken.ThrowIfCancellationRequested(); 113 | int toRead = (int)Math.Min(count, _bytesRemaining); 114 | int read = await _inner.ReadAsync(buffer, offset, toRead, cancellationToken); 115 | UpdateBytesRemaining(read); 116 | return read; 117 | } 118 | 119 | public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 120 | { 121 | TaskCompletionSource tcs = new TaskCompletionSource(state); 122 | InternalReadAsync(buffer, offset, count, callback, tcs); 123 | return tcs.Task; 124 | } 125 | private async void InternalReadAsync(byte[] buffer, int offset, int count, AsyncCallback callback, TaskCompletionSource tcs) 126 | { 127 | try 128 | { 129 | int read = await ReadAsync(buffer, offset, count); 130 | tcs.TrySetResult(read); 131 | } 132 | catch (Exception ex) 133 | { 134 | tcs.TrySetException(ex); 135 | } 136 | 137 | try 138 | { 139 | callback(tcs.Task); 140 | } 141 | catch (Exception) 142 | { 143 | } 144 | } 145 | 146 | public override int EndRead(IAsyncResult asyncResult) 147 | { 148 | Task t = (Task)asyncResult; 149 | t.Wait(); 150 | 151 | if (t.IsFaulted) 152 | { 153 | throw new IOException(string.Empty, t.Exception); 154 | } 155 | return t.Result; 156 | } 157 | 158 | protected override void Dispose(bool disposing) 159 | { 160 | if (disposing) 161 | { 162 | // TODO: Sync drain with timeout if small number of bytes remaining? This will let us re-use the connection. 163 | _inner.Dispose(); 164 | } 165 | } 166 | 167 | private void CheckDisposed() 168 | { 169 | if (_disposed) 170 | { 171 | throw new ObjectDisposedException(typeof(ContentLengthReadStream).FullName); 172 | } 173 | } 174 | 175 | public override void Write(byte[] buffer, int offset, int count) 176 | { 177 | throw new NotSupportedException(); 178 | } 179 | 180 | public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) 181 | { 182 | throw new NotSupportedException(); 183 | } 184 | 185 | public override void EndWrite(IAsyncResult asyncResult) 186 | { 187 | throw new NotSupportedException(); 188 | } 189 | 190 | public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) 191 | { 192 | throw new NotSupportedException(); 193 | } 194 | 195 | public override long Seek(long offset, SeekOrigin origin) 196 | { 197 | throw new NotSupportedException(); 198 | } 199 | 200 | public override void SetLength(long value) 201 | { 202 | throw new NotSupportedException(); 203 | } 204 | 205 | public override void Flush() 206 | { 207 | throw new NotSupportedException(); 208 | } 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/HttpConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace Microsoft.Net.Http.Client 12 | { 13 | public class HttpConnection : IDisposable 14 | { 15 | private const string CRLF = "\r\n"; 16 | 17 | public HttpConnection(BufferedReadStream transport) 18 | { 19 | Transport = transport; 20 | } 21 | 22 | public BufferedReadStream Transport { get; private set; } 23 | 24 | public async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 25 | { 26 | try 27 | { 28 | // Serialize headers & send 29 | string rawRequest = SerializeRequest(request); 30 | byte[] requestBytes = Encoding.ASCII.GetBytes(rawRequest); 31 | await Transport.WriteAsync(requestBytes, 0, requestBytes.Length, cancellationToken); 32 | 33 | // TODO: Determin if there's a request body? 34 | // Wait for 100-continue? 35 | // Send body 36 | 37 | // Receive headers 38 | List responseLines = await ReadResponseLinesAsync(cancellationToken); 39 | // Determine response type (Chunked, Content-Length, opaque, none...) 40 | // Receive body 41 | return CreateResponseMessage(responseLines); 42 | } 43 | catch (Exception ex) 44 | { 45 | Dispose(); // Any errors at this layer abort the connection. 46 | throw new HttpRequestException("The requested failed, see inner exception for details.", ex); 47 | } 48 | } 49 | 50 | private string SerializeRequest(HttpRequestMessage request) 51 | { 52 | StringBuilder builder = new StringBuilder(); 53 | builder.Append(request.Method); 54 | builder.Append(' '); 55 | builder.Append(request.GetAddressLineProperty()); 56 | builder.Append(" HTTP/"); 57 | builder.Append(request.Version.ToString(2)); 58 | builder.Append(CRLF); 59 | 60 | foreach (var header in request.Headers) 61 | { 62 | foreach (var value in header.Value) 63 | { 64 | builder.Append(header.Key); 65 | builder.Append(": "); 66 | builder.Append(value); 67 | builder.Append(CRLF); 68 | } 69 | } 70 | 71 | if (request.Content != null) 72 | { 73 | foreach (var header in request.Content.Headers) 74 | { 75 | foreach (var value in header.Value) 76 | { 77 | builder.Append(header.Key); 78 | builder.Append(": "); 79 | builder.Append(value); 80 | builder.Append(CRLF); 81 | } 82 | } 83 | } 84 | // Headers end with an empty line 85 | builder.Append(CRLF); 86 | return builder.ToString(); 87 | } 88 | 89 | private async Task> ReadResponseLinesAsync(CancellationToken cancellationToken) 90 | { 91 | List lines = new List(); 92 | string line = await Transport.ReadLineAsync(cancellationToken); 93 | while (line.Length > 0) 94 | { 95 | lines.Add(line); 96 | line = await Transport.ReadLineAsync(cancellationToken); 97 | } 98 | return lines; 99 | } 100 | 101 | private HttpResponseMessage CreateResponseMessage(List responseLines) 102 | { 103 | string responseLine = responseLines.First(); 104 | // HTTP/1.1 200 OK 105 | string[] responseLineParts = responseLine.Split(new[] { ' ' }, 3); 106 | // TODO: Verify HTTP/1.0 or 1.1. 107 | if (responseLineParts.Length < 2) 108 | { 109 | throw new HttpRequestException("Invalid response line: " + responseLine); 110 | } 111 | int statusCode = 0; 112 | if (int.TryParse(responseLineParts[1], NumberStyles.None, CultureInfo.InvariantCulture, out statusCode)) 113 | { 114 | // TODO: Validate range 115 | } 116 | else 117 | { 118 | throw new HttpRequestException("Invalid status code: " + responseLineParts[1]); 119 | } 120 | HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)statusCode); 121 | if (responseLineParts.Length >= 3) 122 | { 123 | response.ReasonPhrase = responseLineParts[2]; 124 | } 125 | var content = new HttpConnectionResponseContent(this); 126 | response.Content = content; 127 | 128 | foreach (var rawHeader in responseLines.Skip(1)) 129 | { 130 | int colonOffset = rawHeader.IndexOf(':'); 131 | if (colonOffset <= 0) 132 | { 133 | throw new HttpRequestException("The given header line format is invalid: " + rawHeader); 134 | } 135 | string headerName = rawHeader.Substring(0, colonOffset); 136 | string headerValue = rawHeader.Substring(colonOffset + 2); 137 | if (!response.Headers.TryAddWithoutValidation(headerName, headerValue)) 138 | { 139 | bool success = response.Content.Headers.TryAddWithoutValidation(headerName, headerValue); 140 | System.Diagnostics.Debug.Assert(success, "Failed to add response header: " + rawHeader); 141 | } 142 | } 143 | // After headers have been set 144 | content.ResolveResponseStream(chunked: response.Headers.TransferEncodingChunked.HasValue && response.Headers.TransferEncodingChunked.Value); 145 | 146 | return response; 147 | } 148 | 149 | public void Dispose() 150 | { 151 | Dispose(true); 152 | } 153 | 154 | protected virtual void Dispose(bool disposing) 155 | { 156 | if (disposing) 157 | { 158 | Transport.Dispose(); 159 | } 160 | } 161 | } 162 | } 163 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/HttpConnectionResponseContent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Net.Http; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace Microsoft.Net.Http.Client 11 | { 12 | public class HttpConnectionResponseContent : HttpContent 13 | { 14 | private readonly HttpConnection _connection; 15 | private Stream _responseStream; 16 | 17 | public HttpConnectionResponseContent(HttpConnection connection) 18 | { 19 | _connection = connection; 20 | } 21 | 22 | public void ResolveResponseStream(bool chunked) 23 | { 24 | if (_responseStream != null) 25 | { 26 | throw new InvalidOperationException("Called multiple times"); 27 | } 28 | if (chunked) 29 | { 30 | _responseStream = new ChunkedReadStream(_connection.Transport); 31 | } 32 | else if (Headers.ContentLength.HasValue) 33 | { 34 | _responseStream = new ContentLengthReadStream(_connection.Transport, Headers.ContentLength.Value); 35 | } 36 | else 37 | { 38 | // Raw, read until end and close 39 | _responseStream = _connection.Transport; 40 | } 41 | } 42 | 43 | protected override Task SerializeToStreamAsync(Stream stream, System.Net.TransportContext context) 44 | { 45 | return _responseStream.CopyToAsync(stream); 46 | } 47 | 48 | protected override Task CreateContentReadStreamAsync() 49 | { 50 | return Task.FromResult(_responseStream); 51 | } 52 | 53 | protected override bool TryComputeLength(out long length) 54 | { 55 | length = 0; 56 | return false; 57 | } 58 | 59 | protected override void Dispose(bool disposing) 60 | { 61 | _responseStream.Dispose(); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ManagedHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Net.Security; 7 | using System.Net.Sockets; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | 11 | namespace Microsoft.Net.Http.Client 12 | { 13 | public class ManagedHandler : HttpMessageHandler 14 | { 15 | public ManagedHandler() 16 | { 17 | MaxAutomaticRedirects = 20; 18 | RedirectMode = RedirectMode.NoDowngrade; 19 | } 20 | 21 | public Uri ProxyAddress 22 | { 23 | // TODO: Validate that only an absolute http address is specified. Path, query, and fragment are ignored 24 | get; set; 25 | } 26 | 27 | public int MaxAutomaticRedirects { get; set; } 28 | 29 | public RedirectMode RedirectMode { get; set; } 30 | 31 | protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 32 | { 33 | if (request == null) 34 | { 35 | throw new ArgumentNullException("request"); 36 | } 37 | 38 | HttpResponseMessage response = null; 39 | int redirectCount = 0; 40 | bool retry; 41 | 42 | do 43 | { 44 | retry = false; 45 | response = await ProcessRequestAsync(request, cancellationToken); 46 | if (redirectCount < MaxAutomaticRedirects && IsAllowedRedirectResponse(request, response)) 47 | { 48 | redirectCount++; 49 | retry = true; 50 | } 51 | 52 | } while (retry); 53 | 54 | return response; 55 | } 56 | 57 | private bool IsAllowedRedirectResponse(HttpRequestMessage request, HttpResponseMessage response) 58 | { 59 | // Are redirects enabled? 60 | if (RedirectMode == RedirectMode.None) 61 | { 62 | return false; 63 | } 64 | 65 | // Status codes 301 and 302 66 | if (response.StatusCode != HttpStatusCode.Redirect && response.StatusCode != HttpStatusCode.Moved) 67 | { 68 | return false; 69 | } 70 | 71 | Uri location = response.Headers.Location; 72 | 73 | if (location == null) 74 | { 75 | return false; 76 | } 77 | 78 | if (!location.IsAbsoluteUri) 79 | { 80 | request.RequestUri = location; 81 | request.SetPathAndQueryProperty(null); 82 | request.SetAddressLineProperty(null); 83 | request.Headers.Authorization = null; 84 | return true; 85 | } 86 | 87 | // Check if redirect from https to http is allowed 88 | if (request.IsHttps() && string.Equals("http", location.Scheme, StringComparison.OrdinalIgnoreCase) 89 | && RedirectMode == RedirectMode.NoDowngrade) 90 | { 91 | return false; 92 | } 93 | 94 | // Reset fields calculated from the URI. 95 | request.RequestUri = location; 96 | request.SetSchemeProperty(null); 97 | request.Headers.Host = null; 98 | request.Headers.Authorization = null; 99 | request.SetHostProperty(null); 100 | request.SetConnectionHostProperty(null); 101 | request.SetPortProperty(null); 102 | request.SetConnectionPortProperty(null); 103 | request.SetPathAndQueryProperty(null); 104 | request.SetAddressLineProperty(null); 105 | return true; 106 | } 107 | 108 | private async Task ProcessRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken) 109 | { 110 | cancellationToken.ThrowIfCancellationRequested(); 111 | 112 | ProcessUrl(request); 113 | ProcessHostHeader(request); 114 | request.Headers.ConnectionClose = true; // TODO: Connection re-use is not supported. 115 | 116 | if (request.Method != HttpMethod.Get) 117 | { 118 | throw new NotImplementedException(request.Method.Method); // TODO: POST 119 | } 120 | 121 | ProxyMode proxyMode = DetermineProxyModeAndAddressLine(request); 122 | ApmStream transport = await ConnectAsync(request, cancellationToken); 123 | 124 | if (proxyMode == ProxyMode.Tunnel) 125 | { 126 | await TunnelThroughProxyAsync(request, transport, cancellationToken); 127 | } 128 | 129 | System.Diagnostics.Debug.Assert(!(proxyMode == ProxyMode.Http && request.IsHttps())); 130 | 131 | if (request.IsHttps()) 132 | { 133 | SslStream sslStream = new SslStream(transport); 134 | await sslStream.AuthenticateAsClientAsync(request.GetHostProperty()); 135 | transport = new ApmStreamWrapper(sslStream); 136 | } 137 | 138 | var bufferedReadStream = new BufferedReadStream(transport); 139 | var connection = new HttpConnection(bufferedReadStream); 140 | return await connection.SendAsync(request, cancellationToken); 141 | } 142 | 143 | // Data comes from either the request.RequestUri or from the request.Properties 144 | private void ProcessUrl(HttpRequestMessage request) 145 | { 146 | string scheme = request.GetSchemeProperty(); 147 | if (string.IsNullOrWhiteSpace(scheme)) 148 | { 149 | if (!request.RequestUri.IsAbsoluteUri) 150 | { 151 | throw new InvalidOperationException("Missing URL Scheme"); 152 | } 153 | scheme = request.RequestUri.Scheme; 154 | request.SetSchemeProperty(scheme); 155 | } 156 | if (!(request.IsHttp() || request.IsHttps())) 157 | { 158 | throw new InvalidOperationException("Only HTTP or HTTPS are supported, not: " + request.RequestUri.Scheme); 159 | } 160 | 161 | string host = request.GetHostProperty(); 162 | if (string.IsNullOrWhiteSpace(host)) 163 | { 164 | if (!request.RequestUri.IsAbsoluteUri) 165 | { 166 | throw new InvalidOperationException("Missing URL Scheme"); 167 | } 168 | host = request.RequestUri.DnsSafeHost; 169 | request.SetHostProperty(host); 170 | } 171 | string connectionHost = request.GetConnectionHostProperty(); 172 | if (string.IsNullOrWhiteSpace(connectionHost)) 173 | { 174 | request.SetConnectionHostProperty(host); 175 | } 176 | 177 | int? port = request.GetPortProperty(); 178 | if (!port.HasValue) 179 | { 180 | if (!request.RequestUri.IsAbsoluteUri) 181 | { 182 | throw new InvalidOperationException("Missing URL Scheme"); 183 | } 184 | port = request.RequestUri.Port; 185 | request.SetPortProperty(port); 186 | } 187 | int? connectionPort = request.GetConnectionPortProperty(); 188 | if (!connectionPort.HasValue) 189 | { 190 | request.SetConnectionPortProperty(port); 191 | } 192 | 193 | string pathAndQuery = request.GetPathAndQueryProperty(); 194 | if (string.IsNullOrWhiteSpace(pathAndQuery)) 195 | { 196 | if (request.RequestUri.IsAbsoluteUri) 197 | { 198 | pathAndQuery = request.RequestUri.PathAndQuery; 199 | } 200 | else 201 | { 202 | pathAndQuery = Uri.EscapeUriString(request.RequestUri.ToString()); 203 | } 204 | request.SetPathAndQueryProperty(pathAndQuery); 205 | } 206 | } 207 | 208 | private void ProcessHostHeader(HttpRequestMessage request) 209 | { 210 | if (string.IsNullOrWhiteSpace(request.Headers.Host)) 211 | { 212 | string host = request.GetHostProperty(); 213 | int port = request.GetPortProperty().Value; 214 | if (host.Contains(':')) 215 | { 216 | // IPv6 217 | host = '[' + host + ']'; 218 | } 219 | 220 | request.Headers.Host = host + ":" + port.ToString(CultureInfo.InvariantCulture); 221 | } 222 | } 223 | 224 | private ProxyMode DetermineProxyModeAndAddressLine(HttpRequestMessage request) 225 | { 226 | string scheme = request.GetSchemeProperty(); 227 | string host = request.GetHostProperty(); 228 | int? port = request.GetPortProperty(); 229 | string pathAndQuery = request.GetPathAndQueryProperty(); 230 | string addressLine = request.GetAddressLineProperty(); 231 | 232 | if (string.IsNullOrEmpty(addressLine)) 233 | { 234 | request.SetAddressLineProperty(pathAndQuery); 235 | } 236 | 237 | if (ProxyAddress == null) 238 | { 239 | return ProxyMode.None; 240 | } 241 | if (request.IsHttp()) 242 | { 243 | if (string.IsNullOrEmpty(addressLine)) 244 | { 245 | addressLine = scheme + "://" + host + ":" + port.Value + pathAndQuery; 246 | request.SetAddressLineProperty(addressLine); 247 | } 248 | request.SetConnectionHostProperty(ProxyAddress.DnsSafeHost); 249 | request.SetConnectionPortProperty(ProxyAddress.Port); 250 | return ProxyMode.Http; 251 | } 252 | // Tunneling generates a completely seperate request, don't alter the original, just the connection address. 253 | request.SetConnectionHostProperty(ProxyAddress.DnsSafeHost); 254 | request.SetConnectionPortProperty(ProxyAddress.Port); 255 | return ProxyMode.Tunnel; 256 | } 257 | 258 | private async Task ConnectAsync(HttpRequestMessage request, CancellationToken cancellationToken) 259 | { 260 | TcpClient client = new TcpClient(); 261 | try 262 | { 263 | await client.ConnectAsync(request.GetConnectionHostProperty(), request.GetConnectionPortProperty().Value); 264 | return new ApmStreamWrapper(client.GetStream()); 265 | } 266 | catch (SocketException sox) 267 | { 268 | ((IDisposable)client).Dispose(); 269 | throw new HttpRequestException("Request failed", sox); 270 | } 271 | } 272 | 273 | private async Task TunnelThroughProxyAsync(HttpRequestMessage request, ApmStream transport, CancellationToken cancellationToken) 274 | { 275 | // Send a Connect request: 276 | // CONNECT server.example.com:80 HTTP / 1.1 277 | // Host: server.example.com:80 278 | var connectReqeuest = new HttpRequestMessage(); 279 | connectReqeuest.Headers.ProxyAuthorization = request.Headers.ProxyAuthorization; 280 | connectReqeuest.Method = new HttpMethod("CONNECT"); 281 | // TODO: IPv6 hosts 282 | string authority = request.GetHostProperty() + ":" + request.GetPortProperty().Value; 283 | connectReqeuest.SetAddressLineProperty(authority); 284 | connectReqeuest.Headers.Host = authority; 285 | 286 | HttpConnection connection = new HttpConnection(new BufferedReadStream(transport)); 287 | HttpResponseMessage connectResponse; 288 | try 289 | { 290 | connectResponse = await connection.SendAsync(connectReqeuest, cancellationToken); 291 | // TODO:? await connectResponse.Content.LoadIntoBufferAsync(); // Drain any body 292 | // There's no danger of accidently consuming real response data because the real request hasn't been sent yet. 293 | } 294 | catch (Exception ex) 295 | { 296 | transport.Dispose(); 297 | throw new HttpRequestException("SSL Tunnel failed to initialize", ex); 298 | } 299 | 300 | // Listen for a response. Any 2XX is considered success, anything else is considered a failure. 301 | if ((int)connectResponse.StatusCode < 200 || 300 <= (int)connectResponse.StatusCode) 302 | { 303 | transport.Dispose(); 304 | throw new HttpRequestException("Failed to negotiate the proxy tunnel: " + connectResponse.ToString()); 305 | } 306 | } 307 | } 308 | } 309 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/Microsoft.Net.Http.Client.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {B1B090AB-046C-4B46-BFFB-FAB7B166A5C2} 8 | Library 9 | Properties 10 | Microsoft.Net.Http.Client 11 | Microsoft.Net.Http.Client 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | {62a03c93-8459-4211-a609-6f97d4b046f1} 55 | Microsoft.Net.Security 56 | 57 | 58 | 59 | 66 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/Microsoft.Net.Http.Client.kproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 12.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 9057d304-79fb-4b91-8c28-b7ab22ed20fe 10 | Library 11 | 12 | 13 | ConsoleDebugger 14 | 15 | 16 | WebDebugger 17 | 18 | 19 | 20 | 21 | 22 | 23 | Microsoft.Net.Http.Client 24 | 25 | 26 | Microsoft.Net.Http.Client 27 | 28 | 29 | 2.0 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Microsoft.Net.Http.Client")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Microsoft.Net.Http.Client")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("426e425c-2af7-4997-8379-02c15642e0ef")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/ProxyMode.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Net.Http.Client 2 | { 3 | public enum ProxyMode 4 | { 5 | None, 6 | Http, 7 | Tunnel 8 | } 9 | } -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/RedirectMode.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Net.Http.Client 2 | { 3 | public enum RedirectMode 4 | { 5 | /// 6 | /// Do not follow redirects. 7 | /// 8 | None, 9 | 10 | /// 11 | /// Disallows redirecting from HTTPS to HTTP 12 | /// 13 | NoDowngrade, 14 | 15 | /// 16 | /// Follow all redirects 17 | /// 18 | All, 19 | } 20 | } -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/RequestExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | 4 | namespace Microsoft.Net.Http.Client 5 | { 6 | public static class RequestExtensions 7 | { 8 | public static bool IsHttp(this HttpRequestMessage request) 9 | { 10 | return string.Equals("http", request.GetSchemeProperty(), StringComparison.OrdinalIgnoreCase); 11 | } 12 | 13 | public static bool IsHttps(this HttpRequestMessage request) 14 | { 15 | return string.Equals("https", request.GetSchemeProperty(), StringComparison.OrdinalIgnoreCase); 16 | } 17 | 18 | public static string GetSchemeProperty(this HttpRequestMessage request) 19 | { 20 | return request.GetProperty("url.Scheme"); 21 | } 22 | 23 | public static void SetSchemeProperty(this HttpRequestMessage request, string scheme) 24 | { 25 | request.SetProperty("url.Scheme", scheme); 26 | } 27 | 28 | public static string GetHostProperty(this HttpRequestMessage request) 29 | { 30 | return request.GetProperty("url.Host"); 31 | } 32 | 33 | public static void SetHostProperty(this HttpRequestMessage request, string host) 34 | { 35 | request.SetProperty("url.Host", host); 36 | } 37 | 38 | public static int? GetPortProperty(this HttpRequestMessage request) 39 | { 40 | return request.GetProperty("url.Port"); 41 | } 42 | 43 | public static void SetPortProperty(this HttpRequestMessage request, int? port) 44 | { 45 | request.SetProperty("url.Port", port); 46 | } 47 | 48 | public static string GetConnectionHostProperty(this HttpRequestMessage request) 49 | { 50 | return request.GetProperty("url.ConnectionHost"); 51 | } 52 | 53 | public static void SetConnectionHostProperty(this HttpRequestMessage request, string host) 54 | { 55 | request.SetProperty("url.ConnectionHost", host); 56 | } 57 | 58 | public static int? GetConnectionPortProperty(this HttpRequestMessage request) 59 | { 60 | return request.GetProperty("url.ConnectionPort"); 61 | } 62 | 63 | public static void SetConnectionPortProperty(this HttpRequestMessage request, int? port) 64 | { 65 | request.SetProperty("url.ConnectionPort", port); 66 | } 67 | 68 | public static string GetPathAndQueryProperty(this HttpRequestMessage request) 69 | { 70 | return request.GetProperty("url.PathAndQuery"); 71 | } 72 | 73 | public static void SetPathAndQueryProperty(this HttpRequestMessage request, string pathAndQuery) 74 | { 75 | request.SetProperty("url.PathAndQuery", pathAndQuery); 76 | } 77 | 78 | public static string GetAddressLineProperty(this HttpRequestMessage request) 79 | { 80 | return request.GetProperty("url.AddressLine"); 81 | } 82 | 83 | public static void SetAddressLineProperty(this HttpRequestMessage request, string addressLine) 84 | { 85 | request.SetProperty("url.AddressLine", addressLine); 86 | } 87 | 88 | public static T GetProperty(this HttpRequestMessage request, string key) 89 | { 90 | object obj; 91 | if (request.Properties.TryGetValue(key, out obj)) 92 | { 93 | return (T)obj; 94 | } 95 | return default(T); 96 | } 97 | 98 | public static void SetProperty(this HttpRequestMessage request, string key, T value) 99 | { 100 | request.Properties[key] = value; 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Microsoft.Net.Http.Client/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "dependencies": {}, 4 | "compilationOptions": { 5 | "allowUnsafe": true 6 | }, 7 | "frameworks": { 8 | "net45": { 9 | "frameworkAssemblies": { 10 | "System.Net.Http": "" 11 | } 12 | }, 13 | "aspnet50": { 14 | "frameworkAssemblies": { 15 | "System.Net.Http": "" 16 | } 17 | }, 18 | "aspnetcore50": { 19 | "dependencies": { 20 | "Microsoft.Win32.Primitives": "4.0.0-beta-*", 21 | "System.Collections": "4.0.10-beta-*", 22 | "System.Collections.Concurrent": "4.0.0-beta-*", 23 | "System.Diagnostics.Contracts": "4.0.0-beta-*", 24 | "System.Diagnostics.Debug": "4.0.10-beta-*", 25 | "System.Diagnostics.Tools": "4.0.0-beta-*", 26 | "System.Globalization": "4.0.10-beta-*", 27 | "System.IO": "4.0.0-beta-*", 28 | "System.IO.FileSystem": "4.0.0-beta-*", 29 | "System.Linq": "4.0.0-beta-*", 30 | "System.Net.Primitives": "4.0.10-beta-*", 31 | "System.Net.Http": "4.0.0-beta-*", 32 | "System.Net.Sockets": "4.0.0-beta-*", 33 | "System.Net.Security": "4.0.0-beta-*", 34 | "System.Reflection": "4.0.10-beta-*", 35 | "System.Resources.ResourceManager": "4.0.0-beta-*", 36 | "System.Runtime": "4.0.20-beta-*", 37 | "System.Runtime.Extensions": "4.0.10-beta-*", 38 | "System.Runtime.Handles": "4.0.0-beta-*", 39 | "System.Runtime.InteropServices": "4.0.20-beta-*", 40 | "System.Security.Cryptography.X509Certificates": "4.0.0-beta-*", 41 | "System.Security.Principal": "4.0.0-beta-*", 42 | "System.Text.Encoding": "4.0.10-beta-*", 43 | "System.Text.Encoding.Extensions": "4.0.10-beta-*", 44 | "System.Threading": "4.0.0-beta-*", 45 | "System.Threading.Overlapped": "4.0.0-beta-*", 46 | "System.Threading.Tasks": "4.0.10-beta-*", 47 | "System.Threading.ThreadPool": "4.0.10-beta-*" 48 | } 49 | } 50 | }, 51 | "webroot": null 52 | } -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/HelloWorldTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace Microsoft.Net.Http.Client.FunctionalTests 9 | { 10 | public class HelloWorldTests 11 | { 12 | [Fact] 13 | public async Task GetWithNoBody() 14 | { 15 | string baseAddress; 16 | using (var listener = Utilities.CreateServer(out baseAddress)) 17 | { 18 | var acceptTask = listener.GetContextAsync(); 19 | 20 | using (HttpClient client = new HttpClient(new ManagedHandler())) 21 | { 22 | var requestTask = client.GetAsync(baseAddress); 23 | 24 | var serverContext = await acceptTask; 25 | serverContext.Response.Headers.Add("CustomHeader", "CustomValue"); 26 | serverContext.Response.Close(); 27 | 28 | using (var response = await requestTask) 29 | { 30 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 31 | Assert.Equal("OK", response.ReasonPhrase); 32 | Assert.Equal(new Version(1, 1), response.Version); 33 | Assert.True(response.Headers.Contains("CustomHeader")); 34 | Assert.Equal("CustomValue", response.Headers.GetValues("CustomHeader").First()); 35 | Assert.Equal(0, response.Content.Headers.ContentLength); 36 | Assert.NotNull(response.Content); 37 | Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); 38 | } 39 | } 40 | } 41 | } 42 | 43 | [Fact] 44 | public async Task GetWithContentLengthResponseBody() 45 | { 46 | string baseAddress; 47 | using (var listener = Utilities.CreateServer(out baseAddress)) 48 | { 49 | var acceptTask = listener.GetContextAsync(); 50 | 51 | using (HttpClient client = new HttpClient(new ManagedHandler())) 52 | { 53 | var requestTask = client.GetAsync(baseAddress); 54 | 55 | var serverContext = await acceptTask; 56 | serverContext.Response.ContentLength64 = 100; 57 | serverContext.Response.Close(new byte[100], true); 58 | 59 | using (var response = await requestTask) 60 | { 61 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 62 | Assert.Equal("OK", response.ReasonPhrase); 63 | Assert.Equal(new Version(1, 1), response.Version); 64 | Assert.Equal(100, response.Content.Headers.ContentLength); 65 | Assert.NotNull(response.Content); 66 | Assert.Equal(new byte[100], await response.Content.ReadAsByteArrayAsync()); 67 | } 68 | } 69 | } 70 | } 71 | 72 | [Fact] 73 | public async Task GetWithEmptyChunkedResponseBody() 74 | { 75 | string baseAddress; 76 | using (var listener = Utilities.CreateServer(out baseAddress)) 77 | { 78 | var acceptTask = listener.GetContextAsync(); 79 | 80 | using (HttpClient client = new HttpClient(new ManagedHandler())) 81 | { 82 | var requestTask = client.GetAsync(baseAddress); 83 | 84 | var serverContext = await acceptTask; 85 | serverContext.Response.SendChunked = true; 86 | serverContext.Response.Close(); 87 | 88 | using (var response = await requestTask) 89 | { 90 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 91 | Assert.Equal("OK", response.ReasonPhrase); 92 | Assert.Equal(new Version(1, 1), response.Version); 93 | Assert.True(response.Headers.TransferEncodingChunked.HasValue); 94 | Assert.True(response.Headers.TransferEncodingChunked.Value); 95 | Assert.False(response.Content.Headers.Contains("Content-Length")); 96 | Assert.NotNull(response.Content); 97 | Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); 98 | } 99 | } 100 | } 101 | } 102 | 103 | [Fact] 104 | public async Task GetWithChunkedResponseBody() 105 | { 106 | string baseAddress; 107 | using (var listener = Utilities.CreateServer(out baseAddress)) 108 | { 109 | var acceptTask = listener.GetContextAsync(); 110 | 111 | using (HttpClient client = new HttpClient(new ManagedHandler())) 112 | { 113 | var requestTask = client.GetAsync(baseAddress); 114 | 115 | var serverContext = await acceptTask; 116 | serverContext.Response.OutputStream.Write(new byte[10], 0, 10); 117 | serverContext.Response.OutputStream.Write(new byte[10], 0, 10); 118 | serverContext.Response.Close(); 119 | 120 | using (var response = await requestTask) 121 | { 122 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 123 | Assert.Equal("OK", response.ReasonPhrase); 124 | Assert.Equal(new Version(1, 1), response.Version); 125 | Assert.True(response.Headers.TransferEncodingChunked.HasValue); 126 | Assert.True(response.Headers.TransferEncodingChunked.Value); 127 | Assert.False(response.Content.Headers.Contains("Content-Length")); 128 | Assert.NotNull(response.Content); 129 | Assert.Equal(new byte[20], await response.Content.ReadAsByteArrayAsync()); 130 | } 131 | } 132 | } 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/Microsoft.Net.Http.Client.FunctionalTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {4E567D8C-3A65-431F-9274-AE0BAA108D4F} 8 | Library 9 | Properties 10 | Microsoft.Net.Http.Client.FunctionalTests 11 | Microsoft.Net.Http.Client.FunctionalTests 12 | v4.5 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | ..\..\src\Microsoft.Net.Http.Client\packages\xunit.1.9.2\lib\net20\xunit.dll 43 | 44 | 45 | ..\..\src\Microsoft.Net.Http.Client\packages\xunit.extensions.1.9.2\lib\net20\xunit.extensions.dll 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | {b1b090ab-046c-4b46-bffb-fab7b166a5c2} 58 | Microsoft.Net.Http.Client 59 | 60 | 61 | 62 | 63 | 64 | 65 | 72 | -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/Microsoft.Net.Http.Client.FunctionalTests.kproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 12.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 010c9e4f-a496-43b7-bffc-5e6e2f64552e 10 | Library 11 | 12 | 13 | ConsoleDebugger 14 | 15 | 16 | WebDebugger 17 | 18 | 19 | 20 | 21 | 22 | 23 | 2.0 24 | 25 | 26 | -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Microsoft.Net.Http.Client.FunctionalTests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Microsoft.Net.Http.Client.FunctionalTests")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6b3b0d60-adfe-4989-977e-ee4cc33c2e39")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/RedirectTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | using Xunit; 7 | 8 | namespace Microsoft.Net.Http.Client.FunctionalTests 9 | { 10 | public class RedirectTests 11 | { 12 | [Fact] 13 | public async Task RedirectWithRedirectsDisabled_ReturnsRedirectResponse() 14 | { 15 | string baseAddress; 16 | using (var listener = Utilities.CreateServer(out baseAddress)) 17 | { 18 | var acceptTask = listener.GetContextAsync(); 19 | 20 | using (HttpClient client = new HttpClient(new ManagedHandler() { RedirectMode = RedirectMode.None })) 21 | { 22 | var requestTask = client.GetAsync(baseAddress); 23 | 24 | var serverContext = await acceptTask; 25 | serverContext.Response.Redirect("/Foo"); 26 | serverContext.Response.Close(); 27 | 28 | using (var response = await requestTask) 29 | { 30 | Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); 31 | Assert.Equal("Found", response.ReasonPhrase); 32 | Assert.Equal(new Version(1, 1), response.Version); 33 | Assert.True(response.Headers.Contains("Location")); 34 | Assert.Equal("/Foo", response.Headers.GetValues("Location").First()); 35 | Assert.Equal(0, response.Content.Headers.ContentLength); 36 | Assert.NotNull(response.Content); 37 | Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); 38 | } 39 | } 40 | } 41 | } 42 | 43 | [Fact] 44 | public async Task Redirect_Redirected() 45 | { 46 | string baseAddress; 47 | using (var listener = Utilities.CreateServer(out baseAddress)) 48 | { 49 | var acceptTask = listener.GetContextAsync(); 50 | 51 | using (HttpClient client = new HttpClient(new ManagedHandler())) 52 | { 53 | var requestTask = client.GetAsync(baseAddress); 54 | 55 | var serverContext = await acceptTask; 56 | Assert.Equal("/", serverContext.Request.Url.AbsolutePath); 57 | serverContext.Response.Redirect("/Foo"); 58 | serverContext.Response.Close(); 59 | 60 | serverContext = await listener.GetContextAsync(); 61 | Assert.Equal("/Foo", serverContext.Request.Url.AbsolutePath); 62 | serverContext.Response.Close(); 63 | 64 | using (var response = await requestTask) 65 | { 66 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 67 | Assert.Equal("OK", response.ReasonPhrase); 68 | Assert.Equal(new Version(1, 1), response.Version); 69 | Assert.Equal(0, response.Content.Headers.ContentLength); 70 | Assert.NotNull(response.Content); 71 | Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); 72 | } 73 | } 74 | } 75 | } 76 | 77 | [Fact] 78 | public async Task RedirectLimitHit_RedirectsStop() 79 | { 80 | string baseAddress; 81 | using (var listener = Utilities.CreateServer(out baseAddress)) 82 | { 83 | var acceptTask = listener.GetContextAsync(); 84 | 85 | using (HttpClient client = new HttpClient(new ManagedHandler() { MaxAutomaticRedirects = 2 })) 86 | { 87 | var requestTask = client.GetAsync(baseAddress); 88 | 89 | var serverContext = await acceptTask; 90 | Assert.Equal("/", serverContext.Request.Url.AbsolutePath); 91 | serverContext.Response.Redirect("/1"); 92 | serverContext.Response.Close(); 93 | 94 | serverContext = await listener.GetContextAsync(); 95 | Assert.Equal("/1", serverContext.Request.Url.AbsolutePath); 96 | serverContext.Response.Redirect("/2"); 97 | serverContext.Response.Close(); 98 | 99 | serverContext = await listener.GetContextAsync(); 100 | Assert.Equal("/2", serverContext.Request.Url.AbsolutePath); 101 | serverContext.Response.Redirect("/3"); 102 | serverContext.Response.Close(); 103 | 104 | using (var response = await requestTask) 105 | { 106 | Assert.Equal(HttpStatusCode.Found, response.StatusCode); 107 | Assert.Equal("Found", response.ReasonPhrase); 108 | Assert.Equal(new Version(1, 1), response.Version); 109 | Assert.True(response.Headers.Contains("Location")); 110 | Assert.Equal("/3", response.Headers.GetValues("Location").First()); 111 | Assert.Equal(0, response.Content.Headers.ContentLength); 112 | Assert.NotNull(response.Content); 113 | Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); 114 | } 115 | } 116 | } 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/Utilities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace Microsoft.Net.Http.Client.FunctionalTests 5 | { 6 | public static class Utilities 7 | { 8 | private const int BasePort = 5001; 9 | private const int MaxPort = 10000; 10 | private static int NextPort = BasePort; 11 | private static object PortLock = new object(); 12 | 13 | /// 14 | /// Create a server using a dynamically selected port. 15 | /// 16 | /// 17 | /// 18 | public static HttpListener CreateServer(out string baseAddress) 19 | { 20 | lock (PortLock) 21 | { 22 | while (NextPort < MaxPort) 23 | { 24 | var port = NextPort++; 25 | baseAddress = "http://localhost:" + port + "/"; 26 | var listener = new HttpListener(); 27 | listener.Prefixes.Add(baseAddress); 28 | try 29 | { 30 | listener.Start(); 31 | return listener; 32 | } 33 | catch (HttpListenerException) 34 | { 35 | listener.Close(); 36 | } 37 | } 38 | NextPort = BasePort; 39 | } 40 | throw new Exception("Failed to locate a free port."); 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /test/Microsoft.Net.Http.Client.FunctionalTests/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "commands": { 3 | "test": "Xunit.KRunner" 4 | }, 5 | "dependencies": { 6 | "Microsoft.Net.Http.Client" : "1.0.0-*", 7 | "Xunit.KRunner": "1.0.0-*" 8 | }, 9 | "frameworks": { 10 | "aspnet50": { 11 | "frameworkAssemblies": { 12 | "System.Runtime": "4.0.0.0" 13 | } 14 | } 15 | } 16 | } 17 | --------------------------------------------------------------------------------