├── .gitattributes ├── .gitignore ├── LICENSE.md ├── README.md ├── System.Net.Http.HttpListener.sln ├── global.json ├── src ├── System.Net.Http.HttpListener.UAP │ ├── Abstractions │ │ └── TcpListenerAdapter.UAP.cs │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ └── System.Net.Http.HttpListener.UAP.rd.xml │ ├── System.Net.Http.HttpListener.UAP.csproj │ └── project.json ├── System.Net.Http.HttpListener │ ├── HttpLIstenerHeaderValueCollection.cs │ ├── HttpListener.cs │ ├── HttpListenerContext.cs │ ├── HttpListenerHeaders.cs │ ├── HttpListenerRequest.cs │ ├── HttpListenerRequestEventArgs.cs │ ├── HttpListenerRequestExtensions.cs │ ├── HttpListenerRequestHeaders.cs │ ├── HttpListenerResponse.cs │ ├── HttpListenerResponseHeaders.cs │ ├── HttpMethods.cs │ ├── HttpResponseStatusCodeExtensions.cs │ ├── HttpUtility.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── System.Net.Http.HttpListener.xproj │ ├── TcpClientAdapter.cs │ ├── TcpListenerAdapter.cs │ └── project.json ├── TestApp │ ├── App.xaml │ ├── App.xaml.cs │ ├── Assets │ │ ├── LockScreenLogo.scale-200.png │ │ ├── SplashScreen.scale-200.png │ │ ├── Square150x150Logo.scale-200.png │ │ ├── Square44x44Logo.scale-200.png │ │ ├── Square44x44Logo.targetsize-24_altform-unplated.png │ │ ├── StoreLogo.png │ │ └── Wide310x150Logo.scale-200.png │ ├── MainPage.xaml │ ├── MainPage.xaml.cs │ ├── Package.appxmanifest │ ├── Properties │ │ ├── AssemblyInfo.cs │ │ └── Default.rd.xml │ ├── TestApp.csproj │ └── project.json ├── TestConsoleApp │ ├── Program.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── TestConsoleApp.xproj │ └── project.json └── _build nuget.cmd └── test └── System.Net.Http.HttpListener.Tests ├── HttpListenerTest.cs ├── Properties └── AssemblyInfo.cs ├── System.Net.Http.HttpListener.Tests.xproj └── project.json /.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 | -------------------------------------------------------------------------------- /.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 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | # DNX 42 | project.lock.json 43 | artifacts/ 44 | 45 | *_i.c 46 | *_p.c 47 | *_i.h 48 | *.ilk 49 | *.meta 50 | *.obj 51 | *.pch 52 | *.pdb 53 | *.pgc 54 | *.pgd 55 | *.rsp 56 | *.sbr 57 | *.tlb 58 | *.tli 59 | *.tlh 60 | *.tmp 61 | *.tmp_proj 62 | *.log 63 | *.vspscc 64 | *.vssscc 65 | .builds 66 | *.pidb 67 | *.svclog 68 | *.scc 69 | 70 | # Chutzpah Test files 71 | _Chutzpah* 72 | 73 | # Visual C++ cache files 74 | ipch/ 75 | *.aps 76 | *.ncb 77 | *.opensdf 78 | *.sdf 79 | *.cachefile 80 | 81 | # Visual Studio profiler 82 | *.psess 83 | *.vsp 84 | *.vspx 85 | 86 | # TFS 2012 Local Workspace 87 | $tf/ 88 | 89 | # Guidance Automation Toolkit 90 | *.gpState 91 | 92 | # ReSharper is a .NET coding add-in 93 | _ReSharper*/ 94 | *.[Rr]e[Ss]harper 95 | *.DotSettings.user 96 | 97 | # JustCode is a .NET coding add-in 98 | .JustCode 99 | 100 | # TeamCity is a build add-in 101 | _TeamCity* 102 | 103 | # DotCover is a Code Coverage Tool 104 | *.dotCover 105 | 106 | # NCrunch 107 | _NCrunch_* 108 | .*crunch*.local.xml 109 | 110 | # MightyMoose 111 | *.mm.* 112 | AutoTest.Net/ 113 | 114 | # Web workbench (sass) 115 | .sass-cache/ 116 | 117 | # Installshield output folder 118 | [Ee]xpress/ 119 | 120 | # DocProject is a documentation generator add-in 121 | DocProject/buildhelp/ 122 | DocProject/Help/*.HxT 123 | DocProject/Help/*.HxC 124 | DocProject/Help/*.hhc 125 | DocProject/Help/*.hhk 126 | DocProject/Help/*.hhp 127 | DocProject/Help/Html2 128 | DocProject/Help/html 129 | 130 | # Click-Once directory 131 | publish/ 132 | 133 | # Publish Web Output 134 | *.[Pp]ublish.xml 135 | *.azurePubxml 136 | ## TODO: Comment the next line if you want to checkin your 137 | ## web deploy settings but do note that will include unencrypted 138 | ## passwords 139 | #*.pubxml 140 | 141 | *.publishproj 142 | 143 | # NuGet Packages 144 | *.nupkg 145 | # The packages folder can be ignored because of Package Restore 146 | **/packages/* 147 | # except build/, which is used as an MSBuild target. 148 | !**/packages/build/ 149 | # Uncomment if necessary however generally it will be regenerated when needed 150 | #!**/packages/repositories.config 151 | 152 | # Windows Azure Build Output 153 | csx/ 154 | *.build.csdef 155 | 156 | # Windows Store app package directory 157 | AppPackages/ 158 | 159 | # Visual Studio cache files 160 | # files ending in .cache can be ignored 161 | *.[Cc]ache 162 | # but keep track of directories ending in .cache 163 | !*.[Cc]ache/ 164 | 165 | # Others 166 | ClientBin/ 167 | [Ss]tyle[Cc]op.* 168 | ~$* 169 | *~ 170 | *.dbmdl 171 | *.dbproj.schemaview 172 | *.pfx 173 | *.publishsettings 174 | node_modules/ 175 | orleans.codegen.cs 176 | 177 | # RIA/Silverlight projects 178 | Generated_Code/ 179 | 180 | # Backup & report files from converting an old project file 181 | # to a newer Visual Studio version. Backup files are not needed, 182 | # because we have git ;-) 183 | _UpgradeReport_Files/ 184 | Backup*/ 185 | UpgradeLog*.XML 186 | UpgradeLog*.htm 187 | 188 | # SQL Server files 189 | *.mdf 190 | *.ldf 191 | 192 | # Business Intelligence projects 193 | *.rdl.data 194 | *.bim.layout 195 | *.bim_*.settings 196 | 197 | # Microsoft Fakes 198 | FakesAssemblies/ 199 | 200 | # Node.js Tools for Visual Studio 201 | .ntvs_analysis.dat 202 | 203 | # Visual Studio 6 build log 204 | *.plg 205 | 206 | # Visual Studio 6 workspace options file 207 | *.opt 208 | 209 | # LightSwitch generated files 210 | GeneratedArtifacts/ 211 | _Pvt_Extensions/ 212 | ModelManifest.xml 213 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Robert Sundström 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HttpListener for .NET Core and UWP 2 | 3 | A simple library that essentially allows for building your own HTTP server on .NET Core and the Universal Windows Platform (UWP). 4 | 5 | ## Overview 6 | 7 | This library fills the void left by the missing System.Net.Http.HttpListener in .NET Core and Universal Windows Platform (UWP). 8 | 9 | By targetting .NET Core and UWP, this API enables HTTP server scenarios on Windows 10 for IoT on Raspberry Pi (2 & 3). 10 | 11 | Taking a modern approach, this API is not meant to be entirely compatible with the HttpListener found in the full .NET Framework on Windows desktop. 12 | 13 | Please, be aware that this is an early concept, and thus not ready for production. 14 | 15 | Contributions are most welcome. 16 | 17 | ## Solution 18 | 19 | The solution consists of two projects with a common core targetting: 20 | 21 | 1. .NET Core project - Windows, Linux and Mac OS X. 22 | 2. Universal Windows Platform (UWP) - Windows 10 and up. 23 | 24 | The API:s are generally similar, but may differ slightly on each platform due to their respective API constraints. However, the core concepts remain the same. 25 | 26 | On .NET Core it uses .NET:s TcpListener and TcpClient. 27 | 28 | On UWP it uses Windows Runtime's StreamSocketListener and StreamSocket. 29 | 30 | ## Get the package(s) 31 | 32 | The latest version that has been release can be found in this NuGet feed: 33 | 34 | ``` 35 | https://www.myget.org/F/roberts-core-feed/api/v3/index.json 36 | ``` 37 | 38 | Add this to your Package Sources. 39 | 40 | Search for "HttpListener" and the packages "System.Net.Http.HttpListener" and "System.Net.Http.HttpListener.UWP" should show up. 41 | 42 | Choose the one that is to your liking. 43 | 44 | ## Todo 45 | 46 | Here are some things to consider doing in the future: 47 | 48 | * Rewrite the HttpRequest parser and implement missing features, like authentication and the handling of content types. 49 | * Consolidate the two libraries (.NET Core and UWP) into one single .NET Standard-compliant library when possible to do so. 50 | 51 | ## Sample 52 | 53 | Add the using statement. 54 | 55 | ```CSharp 56 | ... 57 | using System.Net.Http; 58 | ``` 59 | 60 | The code used in this sample should be the same on any platform. 61 | 62 | ```CSharp 63 | var listener = new HttpListener(IPAddress.Parse("127.0.0.1"), 8081); 64 | try 65 | { 66 | listener.Request += async (sender, context) => { 67 | var request = context.Request; 68 | var response = context.Response; 69 | if(request.Method == HttpMethod.Get) 70 | { 71 | await response.WriteAsync($"Hello from Server at: {DateTime.Now}\r\n"); 72 | } 73 | else 74 | { 75 | response.MethodNotAllowed(); 76 | } 77 | // Close the HttpResponse to send it back to the client. 78 | response.Close(); 79 | }; 80 | listener.Start(); 81 | 82 | Console.WriteLine("Press any key to exit."); 83 | Console.ReadKey(); 84 | } 85 | catch(Exception exc) 86 | { 87 | Console.WriteLine(exc.ToString()); 88 | } 89 | finally 90 | { 91 | listener.Close(); 92 | } 93 | ``` 94 | 95 | Visit 127.0.0.1:8081 in your browser. 96 | 97 | Also consider having a look at the unit tests. 98 | -------------------------------------------------------------------------------- /System.Net.Http.HttpListener.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "System.Net.Http.HttpListener", "src\System.Net.Http.HttpListener\System.Net.Http.HttpListener.xproj", "{0ECA641F-BD50-413A-876C-A7D4810EB906}" 7 | EndProject 8 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "System.Net.Http.HttpListener.Tests", "test\System.Net.Http.HttpListener.Tests\System.Net.Http.HttpListener.Tests.xproj", "{C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DF1E746A-72B0-4E19-93B3-5AB10C1FC11C}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{CD898B0D-BE14-44D6-9B9A-8BA97E74CEB6}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E8754D0E-970B-45A6-8B1B-0D5ED15099DE}" 15 | ProjectSection(SolutionItems) = preProject 16 | global.json = global.json 17 | LICENSE.md = LICENSE.md 18 | README.md = README.md 19 | EndProjectSection 20 | EndProject 21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "src\TestApp\TestApp.csproj", "{CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}" 22 | ProjectSection(ProjectDependencies) = postProject 23 | {0ECA641F-BD50-413A-876C-A7D4810EB906} = {0ECA641F-BD50-413A-876C-A7D4810EB906} 24 | EndProjectSection 25 | EndProject 26 | Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "TestConsoleApp", "src\TestConsoleApp\TestConsoleApp.xproj", "{28923ACA-8AA7-489F-BC38-A6CB5C469108}" 27 | EndProject 28 | Global 29 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 30 | Debug|Any CPU = Debug|Any CPU 31 | Debug|ARM = Debug|ARM 32 | Debug|x64 = Debug|x64 33 | Debug|x86 = Debug|x86 34 | Release|Any CPU = Release|Any CPU 35 | Release|ARM = Release|ARM 36 | Release|x64 = Release|x64 37 | Release|x86 = Release|x86 38 | EndGlobalSection 39 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 40 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|ARM.ActiveCfg = Debug|Any CPU 43 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|ARM.Build.0 = Debug|Any CPU 44 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|x64.ActiveCfg = Debug|Any CPU 45 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|x64.Build.0 = Debug|Any CPU 46 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|x86.ActiveCfg = Debug|Any CPU 47 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Debug|x86.Build.0 = Debug|Any CPU 48 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|ARM.ActiveCfg = Release|Any CPU 51 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|ARM.Build.0 = Release|Any CPU 52 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|x64.ActiveCfg = Release|Any CPU 53 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|x64.Build.0 = Release|Any CPU 54 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|x86.ActiveCfg = Release|Any CPU 55 | {0ECA641F-BD50-413A-876C-A7D4810EB906}.Release|x86.Build.0 = Release|Any CPU 56 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|ARM.ActiveCfg = Debug|Any CPU 59 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|ARM.Build.0 = Debug|Any CPU 60 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|x64.ActiveCfg = Debug|Any CPU 61 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|x64.Build.0 = Debug|Any CPU 62 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|x86.ActiveCfg = Debug|Any CPU 63 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Debug|x86.Build.0 = Debug|Any CPU 64 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|ARM.ActiveCfg = Release|Any CPU 67 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|ARM.Build.0 = Release|Any CPU 68 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|x64.ActiveCfg = Release|Any CPU 69 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|x64.Build.0 = Release|Any CPU 70 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|x86.ActiveCfg = Release|Any CPU 71 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E}.Release|x86.Build.0 = Release|Any CPU 72 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|Any CPU.ActiveCfg = Debug|x86 73 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|ARM.ActiveCfg = Debug|ARM 74 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|ARM.Build.0 = Debug|ARM 75 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|ARM.Deploy.0 = Debug|ARM 76 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x64.ActiveCfg = Debug|x64 77 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x64.Build.0 = Debug|x64 78 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x64.Deploy.0 = Debug|x64 79 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x86.ActiveCfg = Debug|x86 80 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x86.Build.0 = Debug|x86 81 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Debug|x86.Deploy.0 = Debug|x86 82 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|Any CPU.ActiveCfg = Release|x86 83 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|ARM.ActiveCfg = Release|ARM 84 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|ARM.Build.0 = Release|ARM 85 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|ARM.Deploy.0 = Release|ARM 86 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x64.ActiveCfg = Release|x64 87 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x64.Build.0 = Release|x64 88 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x64.Deploy.0 = Release|x64 89 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x86.ActiveCfg = Release|x86 90 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x86.Build.0 = Release|x86 91 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B}.Release|x86.Deploy.0 = Release|x86 92 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 93 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|Any CPU.Build.0 = Debug|Any CPU 94 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|ARM.ActiveCfg = Debug|Any CPU 95 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|ARM.Build.0 = Debug|Any CPU 96 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|x64.ActiveCfg = Debug|Any CPU 97 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|x64.Build.0 = Debug|Any CPU 98 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|x86.ActiveCfg = Debug|Any CPU 99 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Debug|x86.Build.0 = Debug|Any CPU 100 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|Any CPU.ActiveCfg = Release|Any CPU 101 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|Any CPU.Build.0 = Release|Any CPU 102 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|ARM.ActiveCfg = Release|Any CPU 103 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|ARM.Build.0 = Release|Any CPU 104 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|x64.ActiveCfg = Release|Any CPU 105 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|x64.Build.0 = Release|Any CPU 106 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|x86.ActiveCfg = Release|Any CPU 107 | {28923ACA-8AA7-489F-BC38-A6CB5C469108}.Release|x86.Build.0 = Release|Any CPU 108 | EndGlobalSection 109 | GlobalSection(SolutionProperties) = preSolution 110 | HideSolutionNode = FALSE 111 | EndGlobalSection 112 | GlobalSection(NestedProjects) = preSolution 113 | {0ECA641F-BD50-413A-876C-A7D4810EB906} = {DF1E746A-72B0-4E19-93B3-5AB10C1FC11C} 114 | {C6FFB78D-EFBB-46C3-A0D1-68BF3436735E} = {CD898B0D-BE14-44D6-9B9A-8BA97E74CEB6} 115 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B} = {DF1E746A-72B0-4E19-93B3-5AB10C1FC11C} 116 | {28923ACA-8AA7-489F-BC38-A6CB5C469108} = {DF1E746A-72B0-4E19-93B3-5AB10C1FC11C} 117 | EndGlobalSection 118 | EndGlobal 119 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "projects": [ "src", "test" ] 3 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener.UAP/Abstractions/TcpListenerAdapter.UAP.cs: -------------------------------------------------------------------------------- 1 | #if WINDOWS_UWP 2 | 3 | using System.IO; 4 | using System.Threading.Tasks; 5 | using Windows.Foundation; 6 | using Windows.Networking; 7 | using Windows.Networking.Sockets; 8 | 9 | namespace System.Net.Http.Abstractions 10 | { 11 | partial class TcpListenerAdapter 12 | { 13 | private StreamSocketListener _listener; 14 | 15 | private void Initialize() 16 | { 17 | _listener = new StreamSocketListener(); 18 | } 19 | 20 | private Task acceptTcpClientAsyncInternal() { 21 | var cts = new TaskCompletionSource(); 22 | TypedEventHandler handler = null; 23 | handler = (sender, e) => 24 | { 25 | var client = new TcpClientAdapter(e.Socket); 26 | cts.SetResult(client); 27 | _listener.ConnectionReceived -= handler; 28 | }; 29 | _listener.ConnectionReceived += handler; 30 | return cts.Task; 31 | } 32 | 33 | public Task StartAsync() 34 | { 35 | return _listener.BindEndpointAsync( 36 | new HostName(LocalEndpoint.Address.ToString()), LocalEndpoint.Port.ToString()).AsTask(); 37 | } 38 | 39 | public void Stop() 40 | { 41 | _listener.Dispose(); 42 | } 43 | 44 | public StreamSocketListener StreamSocketListener 45 | { 46 | get 47 | { 48 | return this._listener; 49 | } 50 | } 51 | 52 | } 53 | 54 | partial class TcpClientAdapter 55 | { 56 | private StreamSocket tcpClient; 57 | 58 | public TcpClientAdapter(StreamSocket tcpClient) 59 | { 60 | this.tcpClient = tcpClient; 61 | 62 | LocalEndPoint = new IPEndPoint( 63 | IPAddress.Parse(tcpClient.Information.LocalAddress.ToString()), 64 | int.Parse(tcpClient.Information.LocalPort)); 65 | 66 | RemoteEndPoint = new IPEndPoint( 67 | IPAddress.Parse(tcpClient.Information.RemoteAddress.ToString()), 68 | int.Parse(tcpClient.Information.RemotePort)); 69 | } 70 | 71 | public Stream GetInputStream() 72 | { 73 | return this.tcpClient.InputStream.AsStreamForRead(); 74 | } 75 | 76 | public Stream GetOutputStream() 77 | { 78 | return this.tcpClient.OutputStream.AsStreamForWrite(); 79 | } 80 | 81 | public void Dispose() 82 | { 83 | this.tcpClient.Dispose(); 84 | } 85 | } 86 | } 87 | 88 | #endif -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener.UAP/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("System.Net.Http.HttpListener")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("System.Net.Http.HttpListener")] 13 | [assembly: AssemblyCopyright("Copyright © Robert Sundstrom 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Version information for an assembly consists of the following four values: 18 | // 19 | // Major Version 20 | // Minor Version 21 | // Build Number 22 | // Revision 23 | // 24 | // You can specify all the values or you can default the Build and Revision Numbers 25 | // by using the '*' as shown below: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] 29 | [assembly: ComVisible(false)] -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener.UAP/Properties/System.Net.Http.HttpListener.UAP.rd.xml: -------------------------------------------------------------------------------- 1 | 2 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener.UAP/System.Net.Http.HttpListener.UAP.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {2F531E97-E842-4FD7-A3BF-8ABFA9DB1719} 8 | Library 9 | Properties 10 | System.Net.Http.HttpListener 11 | System.Net.Http.HttpListener 12 | en-US 13 | UAP 14 | 10.0.14393.0 15 | 10.0.10586.0 16 | 14 17 | 512 18 | {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 19 | 20 | 21 | AnyCPU 22 | true 23 | full 24 | false 25 | bin\Debug\ 26 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 27 | prompt 28 | 4 29 | 30 | 31 | AnyCPU 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE;NETFX_CORE;WINDOWS_UWP 36 | prompt 37 | 4 38 | 39 | 40 | x86 41 | true 42 | bin\x86\Debug\ 43 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 44 | ;2008 45 | full 46 | x86 47 | false 48 | prompt 49 | 50 | 51 | x86 52 | bin\x86\Release\ 53 | TRACE;NETFX_CORE;WINDOWS_UWP 54 | true 55 | ;2008 56 | pdbonly 57 | x86 58 | false 59 | prompt 60 | 61 | 62 | ARM 63 | true 64 | bin\ARM\Debug\ 65 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 66 | ;2008 67 | full 68 | ARM 69 | false 70 | prompt 71 | 72 | 73 | ARM 74 | bin\ARM\Release\ 75 | TRACE;NETFX_CORE;WINDOWS_UWP 76 | true 77 | ;2008 78 | pdbonly 79 | ARM 80 | false 81 | prompt 82 | 83 | 84 | x64 85 | true 86 | bin\x64\Debug\ 87 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 88 | ;2008 89 | full 90 | x64 91 | false 92 | prompt 93 | 94 | 95 | x64 96 | bin\x64\Release\ 97 | TRACE;NETFX_CORE;WINDOWS_UWP 98 | true 99 | ;2008 100 | pdbonly 101 | x64 102 | false 103 | prompt 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | Abstractions\TcpListenerAdapter.cs 112 | 113 | 114 | HttpListener.cs 115 | 116 | 117 | HttpListenerHeaders.cs 118 | 119 | 120 | HttpLIstenerHeaderValueCollection.cs 121 | 122 | 123 | HttpListenerRequest.cs 124 | 125 | 126 | HttpListenerRequestEventArgs.cs 127 | 128 | 129 | HttpListenerRequestExtensions.cs 130 | 131 | 132 | HttpListenerRequestHeaders.cs 133 | 134 | 135 | HttpListenerResponse.cs 136 | 137 | 138 | HttpListenerResponseHeaders.cs 139 | 140 | 141 | HttpMethods.cs 142 | 143 | 144 | HttpResponseStatusCodeExtensions.cs 145 | 146 | 147 | HttpUtility.cs 148 | 149 | 150 | 151 | 152 | 153 | 154 | 14.0 155 | 156 | 157 | 164 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener.UAP/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.1-*", 3 | "authors": [ 4 | "Robert Sundstr�m" 5 | ], 6 | "copyright": "Copyright � Robert Sundstr�m 2016", 7 | "packOptions": { 8 | "licenseUrl": "https://github.com/robertsundstrom/HttpListener/blob/master/LICENSE.md", 9 | "projectUrl": "https://github.com/robertsundstrom/HttpListener", 10 | "tags": [ 11 | "Http", 12 | "Web Server" 13 | ] 14 | }, 15 | "buildOptions": { 16 | "debugType": "portable", 17 | "emitEntryPoint": false 18 | }, 19 | "dependencies": { 20 | "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2" 21 | }, 22 | "frameworks": { 23 | "uap10.0": {} 24 | }, 25 | "runtimes": { 26 | "win10-arm": {}, 27 | "win10-arm-aot": {}, 28 | "win10-x86": {}, 29 | "win10-x86-aot": {}, 30 | "win10-x64": {}, 31 | "win10-x64-aot": {} 32 | } 33 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpLIstenerHeaderValueCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | using System.Linq; 3 | using System.Reflection; 4 | using System.Text; 5 | 6 | namespace System.Net.Http 7 | { 8 | public sealed class HttpListenerHeaderValueCollection : Collection 9 | { 10 | internal HttpListenerHeaderValueCollection(HttpListenerHeaders headers, string headerName) 11 | { 12 | Headers = headers; 13 | HeaderName = headerName; 14 | 15 | string valuesString = null; 16 | 17 | if (Headers.TryGetValue(HeaderName, out valuesString)) 18 | { 19 | if (valuesString == null) 20 | return; 21 | 22 | var isString = typeof(T) == typeof(string); 23 | 24 | if (isString) 25 | { 26 | foreach (var value in valuesString.Split(',')) 27 | { 28 | Add((T)(object)value.Trim()); 29 | } 30 | } 31 | else 32 | { 33 | var parseMethod = typeof(T).GetTypeInfo().GetDeclaredMethod("Parse"); 34 | 35 | if (parseMethod == null) 36 | throw new NotSupportedException("Type is not supported."); 37 | 38 | foreach (var value in valuesString.Split(',')) 39 | { 40 | Add((T)parseMethod.Invoke(value.Trim(), new object[0])); 41 | } 42 | } 43 | } 44 | } 45 | 46 | private string HeaderName { get; } 47 | private HttpListenerHeaders Headers { get; } 48 | 49 | protected override void InsertItem(int index, T item) 50 | { 51 | base.InsertItem(index, item); 52 | 53 | Headers[HeaderName] = ToString(); 54 | } 55 | 56 | protected override void ClearItems() 57 | { 58 | base.ClearItems(); 59 | 60 | Headers[HeaderName] = ToString(); 61 | } 62 | 63 | protected override void RemoveItem(int index) 64 | { 65 | base.RemoveItem(index); 66 | 67 | Headers[HeaderName] = ToString(); 68 | } 69 | 70 | protected override void SetItem(int index, T item) 71 | { 72 | base.SetItem(index, item); 73 | 74 | 75 | Headers[HeaderName] = ToString(); 76 | } 77 | public override string ToString() 78 | { 79 | var sb = new StringBuilder(); 80 | var items = this.ToArray(); 81 | foreach (var value in items) 82 | { 83 | sb.Append(value); 84 | if (!value.Equals(this.Last())) 85 | { 86 | sb.Append(", "); 87 | } 88 | } 89 | return sb.ToString(); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListener.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Sockets; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed 6 | #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously 7 | 8 | namespace System.Net.Http 9 | { 10 | /// 11 | /// Listenes for Http requests. 12 | /// 13 | public sealed class HttpListener : IDisposable 14 | { 15 | Task _listener; 16 | private readonly TcpListenerAdapter _tcpListener; 17 | CancellationTokenSource _cts; 18 | private bool disposedValue = false; // To detect redundant calls 19 | private bool _isListening; 20 | 21 | private HttpListener() 22 | { 23 | _cts = null; 24 | } 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// 29 | /// The address. 30 | /// The port. 31 | public HttpListener(IPAddress address, int port) : this() 32 | { 33 | LocalEndpoint = new IPEndPoint(address, port); 34 | 35 | _tcpListener = new TcpListenerAdapter(LocalEndpoint); 36 | } 37 | 38 | /// 39 | /// Initializes a new instance of the class. 40 | /// 41 | /// The endpoint. 42 | public HttpListener(IPEndPoint endpoint) : this() 43 | { 44 | _tcpListener = new TcpListenerAdapter(endpoint); 45 | } 46 | 47 | /// 48 | /// Gets a value indicating whether the HttpListener is running or not. 49 | /// 50 | public bool IsListening => _isListening; 51 | 52 | /// 53 | /// Gets the underlying Socket. 54 | /// 55 | public Socket Socket => _tcpListener.Socket; 56 | 57 | /// 58 | /// Gets the local endpoint on which the StartListenerAsync is running. 59 | /// 60 | public IPEndPoint LocalEndpoint 61 | { 62 | get; 63 | } 64 | 65 | /// 66 | /// Starts the StartListenerAsync. 67 | /// 68 | public void Start() 69 | { 70 | if (disposedValue) 71 | throw new ObjectDisposedException("Object has been disposed."); 72 | 73 | if (_cts != null) 74 | throw new InvalidOperationException("HttpListener is already running."); 75 | 76 | _cts = new CancellationTokenSource(); 77 | _isListening = true; 78 | _listener = Task.Run(StartListenerAsync, _cts.Token); 79 | } 80 | 81 | private async Task StartListenerAsync() 82 | { 83 | try 84 | { 85 | _tcpListener.Start(); 86 | 87 | while (_isListening) 88 | { 89 | // Await request. 90 | 91 | var client = await _tcpListener.AcceptTcpClientAsync().ConfigureAwait(false); 92 | 93 | var request = new HttpListenerRequest(client); 94 | 95 | // Handle request in a separate thread. 96 | 97 | Task.Run(async () => 98 | { 99 | // Process request. 100 | 101 | var response = new HttpListenerResponse(request, client); 102 | 103 | try 104 | { 105 | await request.ProcessAsync(); 106 | 107 | response.Initialize(); 108 | 109 | if (Request == null) 110 | { 111 | // No Request handlers exist. Respond with "Not Found". 112 | 113 | response.NotFound(); 114 | response.Close(); 115 | } 116 | else 117 | { 118 | // Invoke Request handlers. 119 | 120 | Request(this, new HttpListenerRequestEventArgs(request, response)); 121 | } 122 | } 123 | catch (Exception) 124 | { 125 | response.CloseSocket(); 126 | } 127 | }); 128 | } 129 | } 130 | catch (Exception) 131 | { 132 | throw; 133 | } 134 | finally 135 | { 136 | _isListening = false; 137 | _cts = null; 138 | } 139 | } 140 | 141 | /// 142 | /// Closes the StartListenerAsync. 143 | /// 144 | public void Close() 145 | { 146 | if (_cts == null) 147 | throw new InvalidOperationException("HttpListener is not running."); 148 | 149 | Request = null; 150 | 151 | _cts.Cancel(); 152 | _cts = null; 153 | 154 | _isListening = false; 155 | _tcpListener.Stop(); 156 | 157 | try 158 | { 159 | // Stop task 160 | _listener.Wait(TimeSpan.FromMilliseconds(1)); 161 | } 162 | catch (Exception) 163 | { 164 | } 165 | } 166 | 167 | /// 168 | /// Awaits the next HTTP request and returns its context. 169 | /// 170 | /// 171 | public Task GetContextAsync() 172 | { 173 | // Await a Request and return the context to caller. 174 | 175 | var tcs = new TaskCompletionSource(); 176 | EventHandler requestHandler = null; 177 | requestHandler = (sender, evArgs) => 178 | { 179 | var context = new HttpListenerContext(evArgs.Request, evArgs.Response); 180 | tcs.SetResult(context); 181 | Request -= requestHandler; 182 | }; 183 | Request += requestHandler; 184 | return tcs.Task; 185 | } 186 | 187 | public event EventHandler Request; 188 | 189 | #region IDisposable Support 190 | 191 | void Dispose(bool disposing) 192 | { 193 | if (!disposedValue) 194 | { 195 | if (disposing) 196 | { 197 | // TODO: dispose managed state (managed objects). 198 | } 199 | 200 | // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. 201 | // TODO: set large fields to null. 202 | 203 | Close(); 204 | 205 | disposedValue = true; 206 | } 207 | } 208 | 209 | // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. 210 | // ~HttpListener() { 211 | // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 212 | // Dispose(false); 213 | // } 214 | 215 | // This code added to correctly implement the disposable pattern. 216 | public void Dispose() 217 | { 218 | // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 219 | Dispose(true); 220 | // TODO: uncomment the following line if the finalizer is overridden above. 221 | // GC.SuppressFinalize(this); 222 | } 223 | #endregion 224 | } 225 | } 226 | 227 | #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously 228 | #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerContext.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public class HttpListenerContext 4 | { 5 | private readonly HttpListenerResponse response; 6 | 7 | public HttpListenerContext(HttpListenerRequest request, HttpListenerResponse response) 8 | { 9 | Request = request; 10 | this.response = response; 11 | } 12 | 13 | public HttpListenerRequest Request { get; } 14 | 15 | public HttpListenerResponse Response => response; 16 | } 17 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerHeaders.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | 4 | namespace System.Net.Http 5 | { 6 | public class HttpListenerHeaders : Dictionary 7 | { 8 | private HttpListenerHeaderValueCollection contentType; 9 | private HttpListenerHeaderValueCollection connection; 10 | private string contentMD5; 11 | private bool? isRequestHeaders; 12 | 13 | private HttpListenerResponse response; 14 | private HttpListenerRequest request; 15 | 16 | internal void ParseHeaderLines(IEnumerable lines) 17 | { 18 | foreach (var headerLine in lines) 19 | { 20 | var parts = headerLine.Split(':'); 21 | var key = parts[0]; 22 | var value = parts[1].Trim(); 23 | Add(key, value); 24 | } 25 | } 26 | 27 | private string MakeHeaderString() 28 | { 29 | var sb = new StringBuilder(); 30 | foreach (var header in this) 31 | { 32 | sb.Append($"{header.Key}: {header.Value}\r\n"); 33 | } 34 | return sb.ToString(); 35 | } 36 | 37 | public override string ToString() 38 | { 39 | return MakeHeaderString(); 40 | } 41 | 42 | public HttpListenerHeaderValueCollection Connection 43 | { 44 | get 45 | { 46 | if (connection == null) 47 | { 48 | connection = new HttpListenerHeaderValueCollection(this, "Connection"); 49 | } 50 | return connection; 51 | } 52 | } 53 | 54 | #region Content Headers 55 | 56 | public HttpListenerHeaderValueCollection ContentType 57 | { 58 | get 59 | { 60 | if (contentType == null) 61 | { 62 | contentType = new HttpListenerHeaderValueCollection(this, "Content-Type"); 63 | } 64 | return contentType; 65 | } 66 | } 67 | 68 | public long ContentLength 69 | { 70 | get 71 | { 72 | if (IsRequestHeaders) 73 | { 74 | string headerValue = string.Empty; 75 | if (TryGetValue("Content-Length", out headerValue)) 76 | { 77 | return int.Parse((string)headerValue); 78 | } 79 | return -1; 80 | } 81 | else 82 | { 83 | var response = GetResponse(); 84 | return response.OutputStream.Length; 85 | } 86 | } 87 | } 88 | 89 | public string ContentMd5 90 | { 91 | get 92 | { 93 | if (contentMD5 == null) 94 | { 95 | if (TryGetValue("Content-MD5", out contentMD5)) 96 | { 97 | return contentMD5; 98 | } 99 | } 100 | return null; 101 | } 102 | 103 | #endregion 104 | } 105 | 106 | private bool IsRequestHeaders 107 | { 108 | get 109 | { 110 | if (isRequestHeaders == null) 111 | { 112 | isRequestHeaders = this is HttpListenerRequestHeaders; 113 | } 114 | return isRequestHeaders.GetValueOrDefault(); 115 | } 116 | } 117 | 118 | private void ThrowIfSetterNotSupported() 119 | { 120 | if (IsRequestHeaders) 121 | throw new NotSupportedException("This header cannot be set for requests."); 122 | } 123 | 124 | private HttpListenerRequest GetRequest() 125 | { 126 | if (response == null) 127 | { 128 | var headers = this as HttpListenerRequestHeaders; 129 | request = headers.Request; 130 | } 131 | return request; 132 | } 133 | 134 | private HttpListenerResponse GetResponse() 135 | { 136 | if (response == null) 137 | { 138 | var headers = this as HttpListenerResponseHeaders; 139 | response = headers.Response; 140 | } 141 | return response; 142 | } 143 | } 144 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerRequest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace System.Net.Http 8 | { 9 | public sealed class HttpListenerRequest 10 | { 11 | private TcpClientAdapter client; 12 | 13 | internal HttpListenerRequest(TcpClientAdapter client) 14 | { 15 | this.client = client; 16 | 17 | Headers = new HttpListenerRequestHeaders(this); 18 | } 19 | 20 | internal async Task ProcessAsync() 21 | { 22 | var reader = new StreamReader(client.GetInputStream()); 23 | 24 | StringBuilder request = await ReadRequest(reader); 25 | 26 | var localEndpoint = client.LocalEndPoint; 27 | var remoteEnpoint = client.RemoteEndPoint; 28 | 29 | // This code needs to be rewritten and simplified. 30 | 31 | var requestLines = request.ToString().Split('\n'); 32 | string requestMethod = requestLines[0].TrimEnd('\r'); 33 | string[] requestParts = requestMethod.Split(' '); 34 | 35 | LocalEndpoint = (IPEndPoint)localEndpoint; 36 | RemoteEndpoint = (IPEndPoint)remoteEnpoint; 37 | 38 | var lines = request.ToString().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); 39 | 40 | ParseHeaders(lines); 41 | ParseRequestLine(lines); 42 | 43 | await PrepareInputStream(reader); 44 | } 45 | 46 | private void ParseRequestLine(string[] lines) 47 | { 48 | var line = lines.ElementAt(0).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 49 | 50 | var url = new UriBuilder(Headers.Host + line[1]).Uri; 51 | var httpMethod = line[0]; 52 | 53 | Version = line[2]; 54 | Method = httpMethod; 55 | RequestUri = url; 56 | } 57 | 58 | private async Task PrepareInputStream(StreamReader reader) 59 | { 60 | if (Method == HttpMethods.Post || Method == HttpMethods.Put || Method == HttpMethods.Patch) 61 | { 62 | Encoding encoding = Encoding.UTF8; 63 | 64 | var contentLength = (int)Headers.ContentLength; 65 | 66 | char[] buffer = new char[contentLength]; 67 | 68 | await reader.ReadAsync(buffer, 0, contentLength); 69 | 70 | InputStream = new MemoryStream(encoding.GetBytes(buffer)); 71 | } 72 | } 73 | 74 | private void ParseHeaders(IEnumerable lines) 75 | { 76 | lines = lines.Skip(1); 77 | Headers.ParseHeaderLines(lines); 78 | } 79 | 80 | private static async Task ReadRequest(StreamReader reader) 81 | { 82 | var request = new StringBuilder(); 83 | 84 | string line = null; 85 | while ((line = await reader.ReadLineAsync()) != "") 86 | { 87 | request.AppendLine(line); 88 | } 89 | 90 | var requestStr = request.ToString(); 91 | return request; 92 | } 93 | 94 | /// 95 | /// Gets the endpoint of the listener that received the request. 96 | /// 97 | public IPEndPoint LocalEndpoint { get; private set; } 98 | 99 | /// 100 | /// Gets the endpoint that sent the request. 101 | /// 102 | public IPEndPoint RemoteEndpoint { get; private set; } 103 | 104 | /// 105 | /// Gets the URI send with the request. 106 | /// 107 | public Uri RequestUri { get; private set; } 108 | 109 | /// 110 | /// Gets the HTTP method. 111 | /// 112 | public string Method { get; private set; } 113 | 114 | /// 115 | /// Gets the headers of the HTTP request. 116 | /// 117 | public HttpListenerRequestHeaders Headers { get; private set; } 118 | 119 | /// 120 | /// Gets the stream containing the content sent with the request. 121 | /// 122 | public Stream InputStream { get; private set; } 123 | 124 | /// 125 | /// Gets the HTTP version. 126 | /// 127 | public string Version { get; private set; } 128 | 129 | /// 130 | /// Gets a value indicating whether the request was sent locally or not. 131 | /// 132 | public bool IsLocal 133 | { 134 | get 135 | { 136 | return RemoteEndpoint.Address.Equals(LocalEndpoint.Address); 137 | } 138 | } 139 | 140 | /// 141 | /// Reads the content of the request as a string. 142 | /// 143 | /// 144 | public async Task ReadContentAsStringAsync() 145 | { 146 | var length = InputStream.Length; 147 | byte[] buffer = new byte[length]; 148 | await InputStream.ReadAsync(buffer, 0, (int)length); 149 | return Encoding.UTF8.GetString(buffer); 150 | } 151 | } 152 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerRequestEventArgs.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public sealed class HttpListenerRequestEventArgs : EventArgs 4 | { 5 | internal HttpListenerRequestEventArgs(HttpListenerRequest request, HttpListenerResponse response) 6 | { 7 | Request = request; 8 | Response = response; 9 | } 10 | 11 | /// 12 | /// Gets the Request. 13 | /// 14 | public HttpListenerRequest Request { get; private set; } 15 | 16 | /// 17 | /// Gets the Response. 18 | /// 19 | public HttpListenerResponse Response { get; private set; } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerRequestExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | 4 | namespace System.Net.Http 5 | { 6 | public static class HttpListenerRequestExtensions 7 | { 8 | /// 9 | /// Parse the query parameters. 10 | /// 11 | /// 12 | /// 13 | public static IDictionary ParseQueryParameters(this Uri uri) 14 | { 15 | var query = uri.Query; 16 | var data = HttpUtility.ParseQueryString(query); 17 | 18 | var values = new Dictionary(); 19 | 20 | foreach (var valuePair in data) 21 | { 22 | var value = HttpUtility.UrlDecode(valuePair.Value); 23 | values[valuePair.Key] = valuePair.Value; 24 | } 25 | 26 | return values; 27 | } 28 | 29 | /// 30 | /// Reads URL encoded content from the request. 31 | /// 32 | /// 33 | /// 34 | public static async Task> ReadUrlEncodedContentAsync(this HttpListenerRequest request) 35 | { 36 | var content = await request.ReadContentAsStringAsync(); 37 | var data = HttpUtility.ParseQueryString(content); 38 | 39 | var values = new Dictionary(); 40 | 41 | foreach(var valuePair in data) 42 | { 43 | var value = HttpUtility.UrlDecode(valuePair.Value); 44 | values[valuePair.Key] = valuePair.Value; 45 | } 46 | 47 | return values; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerRequestHeaders.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public sealed class HttpListenerRequestHeaders : HttpListenerHeaders 4 | { 5 | private HttpListenerHeaderValueCollection accept; 6 | private HttpListenerHeaderValueCollection acceptCharset; 7 | private HttpListenerHeaderValueCollection acceptLanguage; 8 | private HttpListenerHeaderValueCollection acceptEncoding; 9 | private DateTime accepDatetime; 10 | private string host; 11 | 12 | public HttpListenerRequestHeaders(HttpListenerRequest request) 13 | { 14 | Request = request; 15 | } 16 | 17 | public string Host 18 | { 19 | get 20 | { 21 | if (host == null) 22 | { 23 | var hostString = string.Empty; 24 | if (TryGetValue("Host", out hostString)) 25 | { 26 | host = hostString; 27 | } 28 | } 29 | return host; 30 | } 31 | } 32 | 33 | #region Accept Headers 34 | 35 | public HttpListenerHeaderValueCollection Accept 36 | { 37 | get 38 | { 39 | if (accept == null) 40 | { 41 | accept = new HttpListenerHeaderValueCollection(this, "Accept"); 42 | } 43 | return accept; 44 | } 45 | } 46 | 47 | public HttpListenerHeaderValueCollection AcceptEncoding 48 | { 49 | get 50 | { 51 | if (acceptEncoding == null) 52 | { 53 | acceptEncoding = new HttpListenerHeaderValueCollection(this, "Accept-Encoding"); 54 | } 55 | return acceptEncoding; 56 | } 57 | } 58 | 59 | public HttpListenerHeaderValueCollection AcceptCharset 60 | { 61 | get 62 | { 63 | if (acceptCharset == null) 64 | { 65 | acceptCharset = new HttpListenerHeaderValueCollection(this, "Accept-Charset"); 66 | } 67 | return acceptCharset; 68 | } 69 | } 70 | 71 | public HttpListenerHeaderValueCollection AcceptLanguage 72 | { 73 | get 74 | { 75 | if (acceptLanguage == null) 76 | { 77 | acceptLanguage = new HttpListenerHeaderValueCollection(this, "Accept-Language"); 78 | } 79 | return acceptLanguage; 80 | } 81 | } 82 | 83 | public DateTime AcceptDateTime 84 | { 85 | get 86 | { 87 | if (accepDatetime == default(DateTime)) 88 | { 89 | string headerValue = string.Empty; 90 | if(TryGetValue("Accept-Datetime", out headerValue)) 91 | { 92 | accepDatetime = DateTime.Parse(headerValue); 93 | } 94 | } 95 | return accepDatetime; 96 | } 97 | } 98 | 99 | internal HttpListenerRequest Request { get; set; } 100 | 101 | #endregion 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerResponse.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | using System.Threading.Tasks; 4 | 5 | namespace System.Net.Http 6 | { 7 | public sealed class HttpListenerResponse : IDisposable 8 | { 9 | private TcpClientAdapter client; 10 | 11 | internal HttpListenerResponse(HttpListenerRequest request, TcpClientAdapter client) 12 | { 13 | Headers = new HttpListenerResponseHeaders(this); 14 | 15 | this.client = client; 16 | Request = request; 17 | } 18 | 19 | internal void Initialize() 20 | { 21 | OutputStream = new MemoryStream(); 22 | 23 | Version = Request.Version; 24 | StatusCode = 200; 25 | ReasonPhrase = "OK"; 26 | } 27 | 28 | HttpListenerRequest Request { get; set; } 29 | 30 | /// 31 | /// Gets the headers of the HTTP response. 32 | /// 33 | public HttpListenerResponseHeaders Headers { get; private set; } 34 | 35 | /// 36 | /// Gets the stream containing the content of this response. 37 | /// 38 | public Stream OutputStream { get; private set; } 39 | 40 | /// 41 | /// Gets or sets the HTTP version. 42 | /// 43 | public string Version { get; set; } 44 | 45 | /// 46 | /// Gets or sets the HTTP status code. 47 | /// 48 | public int StatusCode { get; set; } 49 | 50 | /// 51 | /// Gets or sets the HTTP reason phrase. 52 | /// 53 | public string ReasonPhrase { get; set; } 54 | 55 | private async Task SendMessage() 56 | { 57 | var outputStream = OutputStream as MemoryStream; 58 | outputStream.Seek(0, SeekOrigin.Begin); 59 | 60 | var socketStream = client.GetOutputStream(); 61 | 62 | string header = $"{Version} {StatusCode} {ReasonPhrase}\r\n" + 63 | Headers + 64 | $"Content-Length: {outputStream.Length}\r\n" + 65 | "\r\n"; 66 | 67 | byte[] headerArray = Encoding.UTF8.GetBytes(header); 68 | await socketStream.WriteAsync(headerArray, 0, headerArray.Length); 69 | await outputStream.CopyToAsync(socketStream); 70 | 71 | await socketStream.FlushAsync(); 72 | 73 | } 74 | 75 | /// 76 | /// Writes a string to OutputStream. 77 | /// 78 | /// 79 | /// 80 | public Task WriteContentAsync(string text) 81 | { 82 | var buffer = Encoding.UTF8.GetBytes(text); 83 | return OutputStream.WriteAsync(buffer, 0, buffer.Length); 84 | } 85 | 86 | /// 87 | /// Closes this response and sends it. 88 | /// 89 | public async void Close() 90 | { 91 | await SendMessage(); 92 | CloseSocket(); 93 | } 94 | 95 | internal void CloseSocket() 96 | { 97 | client.Dispose(); 98 | } 99 | 100 | /// 101 | /// Writes a HTTP redirect response. 102 | /// 103 | /// 104 | /// 105 | public async Task RedirectAsync(Uri redirectLocation) 106 | { 107 | var outputStream = client.GetOutputStream(); 108 | 109 | StatusCode = 301; 110 | ReasonPhrase = "Moved permanently"; 111 | Headers.Location = redirectLocation; 112 | 113 | string header = $"{Version} {StatusCode} {ReasonPhrase}\r\n" + 114 | $"Location: {Headers.Location}" + 115 | $"Content-Length: 0\r\n" + 116 | "Connection: close\r\n" + 117 | "\r\n"; 118 | 119 | byte[] headerArray = Encoding.UTF8.GetBytes(header); 120 | await outputStream.WriteAsync(headerArray, 0, headerArray.Length); 121 | await outputStream.FlushAsync(); 122 | 123 | } 124 | 125 | #region IDisposable Support 126 | private bool disposedValue = false; // To detect redundant calls 127 | 128 | void Dispose(bool disposing) 129 | { 130 | if (!disposedValue) 131 | { 132 | if (disposing) 133 | { 134 | // TODO: dispose managed state (managed objects). 135 | } 136 | 137 | Close(); 138 | 139 | // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. 140 | // TODO: set large fields to null. 141 | 142 | disposedValue = true; 143 | } 144 | } 145 | 146 | // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. 147 | // ~HttpListenerResponse() { 148 | // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 149 | // Dispose(false); 150 | // } 151 | 152 | // This code added to correctly implement the disposable pattern. 153 | public void Dispose() 154 | { 155 | // Do not change this code. Put cleanup code in Dispose(bool disposing) above. 156 | Dispose(true); 157 | // TODO: uncomment the following line if the finalizer is overridden above. 158 | // GC.SuppressFinalize(this); 159 | } 160 | #endregion 161 | } 162 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpListenerResponseHeaders.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public sealed class HttpListenerResponseHeaders : HttpListenerHeaders 4 | { 5 | private HttpListenerHeaderValueCollection contentEncoding; 6 | private Uri location; 7 | 8 | public HttpListenerResponseHeaders(HttpListenerResponse response) 9 | { 10 | Response = response; 11 | } 12 | 13 | public Uri Location 14 | { 15 | get 16 | { 17 | if (location == null) 18 | { 19 | string locationString; 20 | if (TryGetValue("Location", out locationString)) 21 | { 22 | location = new Uri(locationString); 23 | } 24 | } 25 | return location; 26 | } 27 | 28 | set 29 | { 30 | if (!value.Equals(location)) 31 | { 32 | location = value; 33 | if (location == null) 34 | return; 35 | this["Location"] = location.ToString(); 36 | } 37 | } 38 | } 39 | 40 | #region Content Headers 41 | 42 | public HttpListenerHeaderValueCollection ContentEncoding => contentEncoding ?? (contentEncoding = new HttpListenerHeaderValueCollection(this, "Content-Encoding")); 43 | 44 | internal HttpListenerResponse Response { get; set; } 45 | 46 | #endregion 47 | } 48 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpMethods.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public static class HttpMethods 4 | { 5 | public readonly static string Post = "POST"; 6 | public readonly static string Get = "GET"; 7 | public readonly static string Patch = "PATCH"; 8 | public readonly static string Put = "PUT"; 9 | public readonly static string Delete = "DELETE"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpResponseStatusCodeExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace System.Net.Http 2 | { 3 | public static class HttpResponseStatusCodeExtensions 4 | { 5 | public static void NotFound(this HttpListenerResponse response) 6 | { 7 | response.StatusCode = 404; 8 | response.ReasonPhrase = "Not Found"; 9 | } 10 | 11 | public static void InternalServerError(this HttpListenerResponse response) 12 | { 13 | response.StatusCode = 500; 14 | response.ReasonPhrase = "Internal Server Error"; 15 | } 16 | 17 | public static void MethodNotAllowed(this HttpListenerResponse response) 18 | { 19 | response.StatusCode = 405; 20 | response.ReasonPhrase = "Method Not Allowed"; 21 | } 22 | 23 | public static void NotImplemented(this HttpListenerResponse response) 24 | { 25 | response.StatusCode = 501; 26 | response.ReasonPhrase = "Not Implemented"; 27 | } 28 | 29 | public static void Forbidden(this HttpListenerResponse response) 30 | { 31 | response.StatusCode = 403; 32 | response.ReasonPhrase = "Forbidden"; 33 | } 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/HttpUtility.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.ObjectModel; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace System.Net.Http 7 | { 8 | /** 9 | /* Source: http://stackoverflow.com/questions/20268544/portable-class-library-pcl-version-of-httputility-parsequerystring 10 | **/ 11 | 12 | public sealed class HttpUtility 13 | { 14 | public static string UrlEncode(string s) 15 | { 16 | string result; 17 | while ((result = Uri.EscapeDataString(s)) != s) 18 | s = result; 19 | return result; 20 | } 21 | 22 | public static string UrlDecode(string s) 23 | { 24 | string result; 25 | while ((result = Uri.UnescapeDataString(s)) != s) 26 | s = result; 27 | return result; 28 | } 29 | 30 | public static HttpValueCollection ParseQueryString(string query) 31 | { 32 | if (query == null) 33 | { 34 | throw new ArgumentNullException(nameof(query)); 35 | } 36 | 37 | if ((query.Length > 0) && (query[0] == '?')) 38 | { 39 | query = query.Substring(1); 40 | } 41 | 42 | return new HttpValueCollection(query, true); 43 | } 44 | } 45 | 46 | public sealed class HttpValue 47 | { 48 | public HttpValue(string key, string value) 49 | { 50 | Key = key; 51 | Value = value; 52 | } 53 | 54 | public string Key { get; set; } 55 | public string Value { get; set; } 56 | } 57 | 58 | public class HttpValueCollection : Collection 59 | { 60 | #region Constructors 61 | 62 | public HttpValueCollection(string query, bool urlencoded) 63 | { 64 | if (!string.IsNullOrEmpty(query)) 65 | { 66 | FillFromString(query, urlencoded); 67 | } 68 | } 69 | 70 | #endregion 71 | 72 | #region Parameters 73 | 74 | public string this[string key] 75 | { 76 | get { return this.First(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)).Value; } 77 | set { this.First(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)).Value = value; } 78 | } 79 | 80 | #endregion 81 | 82 | #region Public Methods 83 | 84 | public void Add(string key, string value) 85 | { 86 | Add(new HttpValue(key, value)); 87 | } 88 | 89 | public bool ContainsKey(string key) 90 | { 91 | return this.Any(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)); 92 | } 93 | 94 | public string[] GetValues(string key) 95 | { 96 | return this.Where(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)).Select(x => x.Value).ToArray(); 97 | } 98 | 99 | public void Remove(string key) 100 | { 101 | this.Where(x => string.Equals(x.Key, key, StringComparison.OrdinalIgnoreCase)) 102 | .ToList() 103 | .ForEach(x => Remove(x)); 104 | } 105 | 106 | public override string ToString() 107 | { 108 | return ToString(true); 109 | } 110 | 111 | public virtual string ToString(bool urlencoded) 112 | { 113 | return ToString(urlencoded, null); 114 | } 115 | 116 | public virtual string ToString(bool urlencoded, IDictionary excludeKeys) 117 | { 118 | if (Count == 0) 119 | { 120 | return string.Empty; 121 | } 122 | 123 | StringBuilder stringBuilder = new StringBuilder(); 124 | 125 | foreach (HttpValue item in this) 126 | { 127 | string key = item.Key; 128 | 129 | if ((excludeKeys == null) || !excludeKeys.Contains(key)) 130 | { 131 | string value = item.Value; 132 | 133 | if (urlencoded) 134 | { 135 | // If .NET 4.5 and above (Thanks @Paya) 136 | key = WebUtility.UrlDecode(key); 137 | // If .NET 4.0 use this instead. 138 | // key = Uri.EscapeDataString(key); 139 | } 140 | 141 | if (stringBuilder.Length > 0) 142 | { 143 | stringBuilder.Append('&'); 144 | } 145 | 146 | stringBuilder.Append((key != null) ? (key + "=") : string.Empty); 147 | 148 | if ((value != null) && (value.Length > 0)) 149 | { 150 | if (urlencoded) 151 | { 152 | value = Uri.EscapeDataString(value); 153 | } 154 | 155 | stringBuilder.Append(value); 156 | } 157 | } 158 | } 159 | 160 | return stringBuilder.ToString(); 161 | } 162 | 163 | #endregion 164 | 165 | #region Private Methods 166 | 167 | private void FillFromString(string query, bool urlencoded) 168 | { 169 | int num = (query != null) ? query.Length : 0; 170 | for (int i = 0; i < num; i++) 171 | { 172 | int startIndex = i; 173 | int num4 = -1; 174 | while (i < num) 175 | { 176 | char ch = query[i]; 177 | if (ch == '=') 178 | { 179 | if (num4 < 0) 180 | { 181 | num4 = i; 182 | } 183 | } 184 | else if (ch == '&') 185 | { 186 | break; 187 | } 188 | i++; 189 | } 190 | string str = null; 191 | string str2 = null; 192 | if (num4 >= 0) 193 | { 194 | str = query.Substring(startIndex, num4 - startIndex); 195 | str2 = query.Substring(num4 + 1, (i - num4) - 1); 196 | } 197 | else 198 | { 199 | str2 = query.Substring(startIndex, i - startIndex); 200 | } 201 | 202 | if (urlencoded) 203 | { 204 | Add(Uri.UnescapeDataString(str), Uri.UnescapeDataString(str2)); 205 | } 206 | else 207 | { 208 | Add(str, str2); 209 | } 210 | 211 | if ((i == (num - 1)) && (query[i] == '&')) 212 | { 213 | Add(null, string.Empty); 214 | } 215 | } 216 | } 217 | 218 | #endregion 219 | } 220 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("System.Net.Http.HttpListener")] 8 | [assembly: AssemblyDescription("HttpListener for .NET Core (DNX)")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("Robert Sundström")] 11 | [assembly: AssemblyProduct("System.Net.Http.HttpListener")] 12 | [assembly: AssemblyCopyright("Copyright © Robert Sundström 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("b3fc0c7e-1a6c-4f10-919b-f5d7ccf34643")] 23 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/System.Net.Http.HttpListener.xproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 0eca641f-bd50-413a-876c-a7d4810eb906 10 | System.Net.Http 11 | .\obj 12 | .\bin\ 13 | 14 | 15 | 2.0 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/TcpClientAdapter.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Net.Sockets; 3 | 4 | namespace System.Net.Http 5 | { 6 | class TcpClientAdapter 7 | { 8 | private readonly TcpClient tcpClient; 9 | 10 | public TcpClientAdapter(TcpClient tcpClient) 11 | { 12 | this.tcpClient = tcpClient; 13 | 14 | LocalEndPoint = (IPEndPoint)tcpClient.Client.LocalEndPoint; 15 | RemoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint; 16 | } 17 | 18 | public IPEndPoint LocalEndPoint 19 | { 20 | get; 21 | private set; 22 | } 23 | 24 | public IPEndPoint RemoteEndPoint 25 | { 26 | get; 27 | private set; 28 | } 29 | 30 | public Stream GetInputStream() 31 | { 32 | return tcpClient.GetStream(); 33 | } 34 | 35 | public Stream GetOutputStream() 36 | { 37 | return tcpClient.GetStream(); 38 | } 39 | 40 | public void Dispose() 41 | { 42 | tcpClient.Dispose(); 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/TcpListenerAdapter.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Sockets; 2 | using System.Threading.Tasks; 3 | 4 | namespace System.Net.Http 5 | { 6 | class TcpListenerAdapter 7 | { 8 | private TcpListener _tcpListener; 9 | 10 | public TcpListenerAdapter(IPEndPoint localEndpoint) 11 | { 12 | LocalEndpoint = localEndpoint; 13 | 14 | Initialize(); 15 | } 16 | 17 | public IPEndPoint LocalEndpoint { get; private set; } 18 | 19 | public Task AcceptTcpClientAsync() 20 | { 21 | return acceptTcpClientInternalAsync(); 22 | } 23 | 24 | private void Initialize() 25 | { 26 | _tcpListener = new TcpListener(LocalEndpoint); 27 | } 28 | 29 | private async Task acceptTcpClientInternalAsync() 30 | { 31 | var tcpClient = await _tcpListener.AcceptTcpClientAsync(); 32 | return new TcpClientAdapter(tcpClient); 33 | } 34 | 35 | public void Start() 36 | { 37 | _tcpListener.Start(); 38 | } 39 | 40 | public void Stop() 41 | { 42 | _tcpListener.Stop(); 43 | } 44 | 45 | public Socket Socket 46 | { 47 | get 48 | { 49 | return _tcpListener.Server; 50 | } 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /src/System.Net.Http.HttpListener/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.1.1", 3 | "authors": [ "Robert Sundström", "Stef Heyenrath" ], 4 | "copyright": "Copyright © Robert Sundström 2016", 5 | "packOptions": { 6 | "licenseUrl": "https://github.com/robertsundstrom/HttpListener/blob/master/LICENSE.md", 7 | "projectUrl": "https://github.com/robertsundstrom/HttpListener", 8 | "tags": [ "Http", "Web Server" ] 9 | }, 10 | 11 | "frameworks": { 12 | "netstandard1.3": { 13 | "buildOptions": { "define": [ "NETSTANDARD" ] }, 14 | "imports": [ 15 | "dotnet5.4" 16 | ], 17 | "dependencies": { 18 | "System.Collections": "4.3.0", 19 | "System.IO": "4.3.0", 20 | "System.Linq": "4.3.0", 21 | "System.Net.Http": "4.3.0", 22 | "System.Net.Sockets": "4.3.0", 23 | "System.Runtime.Extensions": "4.3.0", 24 | "System.Runtime.InteropServices": "4.3.0", 25 | "System.Threading.Tasks": "4.3.0" 26 | } 27 | }, 28 | "uap10.0" : { 29 | "dependencies": { 30 | "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2", 31 | "System.Collections": "4.3.0", 32 | "System.IO": "4.3.0", 33 | "System.Linq": "4.3.0", 34 | "System.Runtime.Extensions": "4.3.0", 35 | "System.Runtime.InteropServices": "4.3.0", 36 | "System.Threading.Tasks": "4.3.0" 37 | } 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /src/TestApp/App.xaml: -------------------------------------------------------------------------------- 1 |  7 | 8 | 9 | -------------------------------------------------------------------------------- /src/TestApp/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Windows.ApplicationModel; 3 | using Windows.ApplicationModel.Activation; 4 | using Windows.UI.Xaml; 5 | using Windows.UI.Xaml.Controls; 6 | using Windows.UI.Xaml.Navigation; 7 | 8 | namespace TestApp 9 | { 10 | /// 11 | /// Provides application-specific behavior to supplement the default Application class. 12 | /// 13 | sealed partial class App : Application 14 | { 15 | /// 16 | /// Initializes the singleton application object. This is the first line of authored code 17 | /// executed, and as such is the logical equivalent of main() or WinMain(). 18 | /// 19 | public App() 20 | { 21 | this.InitializeComponent(); 22 | this.Suspending += OnSuspending; 23 | } 24 | 25 | /// 26 | /// Invoked when the application is launched normally by the end user. Other entry points 27 | /// will be used such as when the application is launched to open a specific file. 28 | /// 29 | /// Details about the launch request and process. 30 | protected override void OnLaunched(LaunchActivatedEventArgs e) 31 | { 32 | #if DEBUG 33 | if (System.Diagnostics.Debugger.IsAttached) 34 | { 35 | this.DebugSettings.EnableFrameRateCounter = true; 36 | } 37 | #endif 38 | Frame rootFrame = Window.Current.Content as Frame; 39 | 40 | // Do not repeat app initialization when the Window already has content, 41 | // just ensure that the window is active 42 | if (rootFrame == null) 43 | { 44 | // Create a Frame to act as the navigation context and navigate to the first page 45 | rootFrame = new Frame(); 46 | 47 | rootFrame.NavigationFailed += OnNavigationFailed; 48 | 49 | if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) 50 | { 51 | //TODO: Load state from previously suspended application 52 | } 53 | 54 | // Place the frame in the current Window 55 | Window.Current.Content = rootFrame; 56 | } 57 | 58 | if (e.PrelaunchActivated == false) 59 | { 60 | if (rootFrame.Content == null) 61 | { 62 | // When the navigation stack isn't restored navigate to the first page, 63 | // configuring the new page by passing required information as a navigation 64 | // parameter 65 | rootFrame.Navigate(typeof(MainPage), e.Arguments); 66 | } 67 | // Ensure the current window is active 68 | Window.Current.Activate(); 69 | } 70 | } 71 | 72 | /// 73 | /// Invoked when Navigation to a certain page fails 74 | /// 75 | /// The Frame which failed navigation 76 | /// Details about the navigation failure 77 | void OnNavigationFailed(object sender, NavigationFailedEventArgs e) 78 | { 79 | throw new Exception("Failed to load Page " + e.SourcePageType.FullName); 80 | } 81 | 82 | /// 83 | /// Invoked when application execution is being suspended. Application state is saved 84 | /// without knowing whether the application will be terminated or resumed with the contents 85 | /// of memory still intact. 86 | /// 87 | /// The source of the suspend request. 88 | /// Details about the suspend request. 89 | private void OnSuspending(object sender, SuspendingEventArgs e) 90 | { 91 | var deferral = e.SuspendingOperation.GetDeferral(); 92 | //TODO: Save application state and stop any background activity 93 | deferral.Complete(); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/TestApp/Assets/LockScreenLogo.scale-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/LockScreenLogo.scale-200.png -------------------------------------------------------------------------------- /src/TestApp/Assets/SplashScreen.scale-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/SplashScreen.scale-200.png -------------------------------------------------------------------------------- /src/TestApp/Assets/Square150x150Logo.scale-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/Square150x150Logo.scale-200.png -------------------------------------------------------------------------------- /src/TestApp/Assets/Square44x44Logo.scale-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/Square44x44Logo.scale-200.png -------------------------------------------------------------------------------- /src/TestApp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/Square44x44Logo.targetsize-24_altform-unplated.png -------------------------------------------------------------------------------- /src/TestApp/Assets/StoreLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/StoreLogo.png -------------------------------------------------------------------------------- /src/TestApp/Assets/Wide310x150Logo.scale-200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marinasundstrom/HttpListener/1686722867a54121b046778bf5e91e37689685c3/src/TestApp/Assets/Wide310x150Logo.scale-200.png -------------------------------------------------------------------------------- /src/TestApp/MainPage.xaml: -------------------------------------------------------------------------------- 1 |  9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/TestApp/MainPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using Windows.UI.Popups; 5 | using Windows.UI.Xaml.Controls; 6 | 7 | // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 8 | 9 | namespace TestApp 10 | { 11 | /// 12 | /// An empty page that can be used on its own or navigated to within a Frame. 13 | /// 14 | public sealed partial class MainPage : Page 15 | { 16 | private HttpListener listener; 17 | 18 | public Uri Url { get; private set; } 19 | 20 | public MainPage() 21 | { 22 | this.InitializeComponent(); 23 | 24 | Initialize(); 25 | } 26 | 27 | private void Initialize() 28 | { 29 | int port = 18081; 30 | 31 | listener = new HttpListener(IPAddress.Any, port); 32 | listener.Request += requestHandler; 33 | listener.Start(); 34 | 35 | bool isListening = listener.IsListening; 36 | } 37 | 38 | private async void requestHandler(object sender, HttpListenerRequestEventArgs e) 39 | { 40 | var request = e.Request; 41 | var response = e.Response; 42 | 43 | if (request.Method == HttpMethods.Get) 44 | { 45 | string content = @"

Hello! What's your name?

46 |
47 | 48 | 49 |
"; 50 | 51 | await response.WriteContentAsync(MakeDocument(content)); 52 | } 53 | else if (request.Method == HttpMethods.Post) 54 | { 55 | var param = request.RequestUri.ParseQueryParameters(); 56 | 57 | var data = await request.ReadUrlEncodedContentAsync(); 58 | var name = data["name"]; 59 | 60 | var content = $"

Hi, {name}! Nice to meet you.

"; 61 | 62 | await response.WriteContentAsync(MakeDocument(content)); 63 | 64 | await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => 65 | { 66 | var dialog = new MessageDialog($"Hi, {name}! Nice to meet you."); 67 | await dialog.ShowAsync(); 68 | }); 69 | } 70 | else 71 | { 72 | response.MethodNotAllowed(); 73 | } 74 | 75 | response.Close(); 76 | } 77 | 78 | private string MakeDocument(object content) 79 | { 80 | return @" 81 | 82 | Test 83 | 84 | " + 85 | content + 86 | @" 87 | "; 88 | } 89 | 90 | ~MainPage() 91 | { 92 | listener.Close(); 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/TestApp/Package.appxmanifest: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | TestApp 7 | robert 8 | Assets\StoreLogo.png 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/TestApp/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("TestApp")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("TestApp")] 12 | [assembly: AssemblyCopyright("Copyright © 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Version information for an assembly consists of the following four values: 17 | // 18 | // Major Version 19 | // Minor Version 20 | // Build Number 21 | // Revision 22 | // 23 | // You can specify all the values or you can default the Build and Revision Numbers 24 | // by using the '*' as shown below: 25 | // [assembly: AssemblyVersion("1.0.*")] 26 | [assembly: AssemblyVersion("1.0.0.0")] 27 | [assembly: AssemblyFileVersion("1.0.0.0")] 28 | [assembly: ComVisible(false)] -------------------------------------------------------------------------------- /src/TestApp/Properties/Default.rd.xml: -------------------------------------------------------------------------------- 1 | 17 | 18 | 19 | 20 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/TestApp/TestApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | x86 7 | {CD908D7A-DEE6-48D3-8E5C-2EBC3851EF4B} 8 | AppContainerExe 9 | Properties 10 | TestApp 11 | TestApp 12 | en-US 13 | UAP 14 | 10.0.14393.0 15 | 10.0.10586.0 16 | 14 17 | 512 18 | {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 19 | TestApp_TemporaryKey.pfx 20 | 21 | 22 | true 23 | bin\x86\Debug\ 24 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 25 | ;2008 26 | full 27 | x86 28 | false 29 | prompt 30 | true 31 | 32 | 33 | bin\x86\Release\ 34 | TRACE;NETFX_CORE;WINDOWS_UWP 35 | true 36 | ;2008 37 | pdbonly 38 | x86 39 | false 40 | prompt 41 | true 42 | true 43 | 44 | 45 | true 46 | bin\ARM\Debug\ 47 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 48 | ;2008 49 | full 50 | ARM 51 | false 52 | prompt 53 | true 54 | 55 | 56 | bin\ARM\Release\ 57 | TRACE;NETFX_CORE;WINDOWS_UWP 58 | true 59 | ;2008 60 | pdbonly 61 | ARM 62 | false 63 | prompt 64 | true 65 | true 66 | 67 | 68 | true 69 | bin\x64\Debug\ 70 | DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP 71 | ;2008 72 | full 73 | x64 74 | false 75 | prompt 76 | true 77 | 78 | 79 | bin\x64\Release\ 80 | TRACE;NETFX_CORE;WINDOWS_UWP 81 | true 82 | ;2008 83 | pdbonly 84 | x64 85 | false 86 | prompt 87 | true 88 | true 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | App.xaml 97 | 98 | 99 | MainPage.xaml 100 | 101 | 102 | 103 | 104 | 105 | Designer 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | MSBuild:Compile 122 | Designer 123 | 124 | 125 | MSBuild:Compile 126 | Designer 127 | 128 | 129 | 130 | 131 | ..\System.Net.Http.HttpListener\bin\$(Configuration)\uap10.0\System.Net.Http.HttpListener.dll 132 | 133 | 134 | 135 | 14.0 136 | 137 | 138 | 145 | -------------------------------------------------------------------------------- /src/TestApp/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "dependencies": { 3 | "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2" 4 | }, 5 | "frameworks": { 6 | "uap10.0": {} 7 | }, 8 | "runtimes": { 9 | "win10-arm": {}, 10 | "win10-arm-aot": {}, 11 | "win10-x86": {}, 12 | "win10-x86-aot": {}, 13 | "win10-x64": {}, 14 | "win10-x64-aot": {} 15 | } 16 | } -------------------------------------------------------------------------------- /src/TestConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | 5 | namespace TestConsoleApp 6 | { 7 | public class Program 8 | { 9 | public static void Main(string[] args) 10 | { 11 | int port = 18081; 12 | 13 | var listener = new HttpListener(IPAddress.Any, port); 14 | listener.Request += HandleRequest; 15 | listener.Start(); 16 | 17 | bool isListening = listener.IsListening; 18 | Console.WriteLine("isListening = {0}", isListening); 19 | 20 | Console.WriteLine("Press any key to stop listener"); 21 | 22 | Console.ReadKey(); 23 | listener.Close(); 24 | listener.Dispose(); 25 | } 26 | 27 | private static async void HandleRequest(object sender, HttpListenerRequestEventArgs e) 28 | { 29 | var request = e.Request; 30 | var response = e.Response; 31 | 32 | if (request.Method == HttpMethods.Get) 33 | { 34 | string content = @"

Hello! What's your name?

35 |
36 | 37 | 38 |
"; 39 | 40 | await response.WriteContentAsync(MakeDocument(content)); 41 | } 42 | else if (request.Method == HttpMethods.Post) 43 | { 44 | var param = request.RequestUri.ParseQueryParameters(); 45 | 46 | var data = await request.ReadUrlEncodedContentAsync(); 47 | var name = data["name"]; 48 | 49 | string content = $"

Hi, {name}! Nice to meet you.

"; 50 | 51 | await response.WriteContentAsync(MakeDocument(content)); 52 | 53 | Console.WriteLine($"--> Hi, {name}! Nice to meet you."); 54 | } 55 | else 56 | { 57 | response.MethodNotAllowed(); 58 | } 59 | 60 | response.Close(); 61 | } 62 | 63 | private static string MakeDocument(object content) 64 | { 65 | return @" 66 | 67 | Test 68 | 69 | " + 70 | content + 71 | @" 72 | "; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/TestConsoleApp/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: AssemblyConfiguration("")] 9 | [assembly: AssemblyCompany("")] 10 | [assembly: AssemblyProduct("TestConsoleApp")] 11 | [assembly: AssemblyTrademark("")] 12 | 13 | // Setting ComVisible to false makes the types in this assembly not visible 14 | // to COM components. If you need to access a type in this assembly from 15 | // COM, set the ComVisible attribute to true on that type. 16 | [assembly: ComVisible(false)] 17 | 18 | // The following GUID is for the ID of the typelib if this project is exposed to COM 19 | [assembly: Guid("28923aca-8aa7-489f-bc38-a6cb5c469108")] 20 | -------------------------------------------------------------------------------- /src/TestConsoleApp/TestConsoleApp.xproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | 10 | 28923aca-8aa7-489f-bc38-a6cb5c469108 11 | TestConsoleApp 12 | .\obj 13 | .\bin\ 14 | v4.5.2 15 | 16 | 17 | 18 | 2.0 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/TestConsoleApp/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "buildOptions": { 4 | "emitEntryPoint": true 5 | }, 6 | 7 | "dependencies": { 8 | "Microsoft.NETCore.App": { 9 | "type": "platform", 10 | "version": "1.1.0" 11 | }, 12 | "System.Net.Http.HttpListener": "1.0.1.1" 13 | }, 14 | 15 | "frameworks": { 16 | "netcoreapp1.0": { 17 | "imports": "dnxcore50" 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/_build nuget.cmd: -------------------------------------------------------------------------------- 1 | dotnet restore 2 | dotnet pack -c Release System.Net.Http.HttpListener\project.json 3 | pause -------------------------------------------------------------------------------- /test/System.Net.Http.HttpListener.Tests/HttpListenerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Xunit; 8 | 9 | namespace Tests 10 | { 11 | public class HttpListenerTest 12 | { 13 | private string address; 14 | private Uri url; 15 | 16 | private HttpListener StartHttpListener(int port, EventHandler requestHandler = null) 17 | { 18 | address = "127.0.0.1"; 19 | url = (new UriBuilder($"http://{address}:{port}/test")).Uri; 20 | 21 | var listener = new HttpListener(IPAddress.Parse(address), port); 22 | if (requestHandler != null) 23 | { 24 | listener.Request += requestHandler; 25 | } 26 | listener.Start(); 27 | 28 | return listener; 29 | } 30 | 31 | [Fact(DisplayName = "GET Request")] 32 | public async Task GetRequest() 33 | { 34 | var listener = StartHttpListener(8081, async (sender, e) => 35 | { 36 | var request = e.Request; 37 | var response = e.Response; 38 | 39 | var x = request.Headers.AcceptEncoding; 40 | 41 | response.Headers.ContentType.Add("application/text"); 42 | 43 | var bytes = Encoding.UTF8.GetBytes("Hello World!"); 44 | await response.OutputStream.WriteAsync(bytes, 0, bytes.Length); 45 | await response.OutputStream.FlushAsync(); 46 | 47 | response.Close(); 48 | }); 49 | 50 | using (var client = new HttpClient()) 51 | { 52 | var response = await client.GetAsync(url); 53 | response.EnsureSuccessStatusCode(); 54 | 55 | var responseContent = await response.Content.ReadAsStringAsync(); 56 | } 57 | 58 | listener.Close(); 59 | } 60 | 61 | [Fact(DisplayName = "POST Request")] 62 | public async Task PostRequest() 63 | { 64 | var listener = StartHttpListener(8082, async (sender, e) => 65 | { 66 | var request = e.Request; 67 | 68 | string content = null; 69 | using (var streamReader = new StreamReader(request.InputStream)) 70 | { 71 | content = await streamReader.ReadToEndAsync(); 72 | } 73 | 74 | var response = e.Response; 75 | 76 | response.Headers.ContentType.Add("text"); 77 | 78 | var bytes = Encoding.UTF8.GetBytes(content); 79 | await response.OutputStream.WriteAsync(bytes, 0, bytes.Length); 80 | await response.OutputStream.FlushAsync(); 81 | 82 | response.Close(); 83 | }); 84 | 85 | using (var client = new HttpClient()) 86 | { 87 | var requestContent = new StringContent("Hey", Encoding.UTF8); 88 | var response = await client.PostAsync(url, requestContent); 89 | response.EnsureSuccessStatusCode(); 90 | 91 | var responseContent = await response.Content.ReadAsStringAsync(); 92 | 93 | Assert.Equal(responseContent, "Hey"); 94 | } 95 | 96 | listener.Close(); 97 | } 98 | 99 | [Fact(Skip = "Not functional")] 100 | public async Task Request() 101 | { 102 | var port = 8083; 103 | var listener = StartHttpListener(port); 104 | //listener.Get(new Uri("/test", UriKind.Relative), async (request, response) => 105 | //{ 106 | // await response.WriteAsync($"Hello from server at: {DateTime.Now}\r\n"); 107 | 108 | // //await Task.Delay(10000); 109 | //}); 110 | 111 | using (var client = new HttpClient()) 112 | { 113 | try 114 | { 115 | //client.Timeout = TimeSpan.FromSeconds(2); 116 | 117 | //var url = (new UriBuilder($"http://{address}:{port}/foo")).Uri; 118 | 119 | var response = await client.GetAsync(url); 120 | response.EnsureSuccessStatusCode(); 121 | 122 | var responseContent = await response.Content.ReadAsStringAsync(); 123 | } 124 | catch (Exception exc) 125 | { 126 | 127 | } 128 | } 129 | 130 | listener.Close(); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /test/System.Net.Http.HttpListener.Tests/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("Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 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("227ecac8-3501-490d-8fc1-28c47868fb3f")] 24 | -------------------------------------------------------------------------------- /test/System.Net.Http.HttpListener.Tests/System.Net.Http.HttpListener.Tests.xproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 14.0 5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 6 | 7 | 8 | 9 | c6ffb78d-efbb-46c3-a0d1-68bf3436735e 10 | System.Net.Http.HttpListener.Tests 11 | .\obj 12 | .\bin\ 13 | 14 | 15 | 2.0 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /test/System.Net.Http.HttpListener.Tests/project.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0-*", 3 | "buildOptions": { 4 | "debugType": "portable", 5 | "emitEntryPoint": false 6 | }, 7 | "dependencies": { 8 | "System.Net.Http.HttpListener": { "target": "project" }, 9 | "xunit": "2.2.0-beta5-build3474", 10 | "dotnet-test-xunit": "2.2.0-preview2-build1029" 11 | }, 12 | "testRunner": "xunit", 13 | "frameworks": { 14 | "netcoreapp1.0": { 15 | "dependencies": { 16 | "Microsoft.NETCore.App": { 17 | "type": "platform", 18 | "version": "1.1.0" 19 | } 20 | }, 21 | "imports": "dnxcore50" 22 | } 23 | } 24 | } 25 | --------------------------------------------------------------------------------