├── .gitignore ├── BasicWebServer.Demo ├── BasicWebServer.Demo.csproj ├── Controllers │ ├── HomeController.cs │ └── UserController.cs ├── Models │ └── FormViewModel.cs ├── Services │ └── UserService.cs ├── Startup.cs ├── Views │ ├── Home │ │ ├── Content.cshtml │ │ ├── Html.cshtml │ │ ├── HtmlFormPost.cshtml │ │ └── Test.cshtml │ ├── Layout.cshtml │ └── User │ │ └── Login.cshtml └── content.txt ├── BasicWebServer.Server ├── Attributes │ ├── AuthorizeAttribute.cs │ ├── HttpGetAttribute.cs │ ├── HttpMethodAttribute.cs │ └── HttpPostAttribute.cs ├── BasicWebServer.Server.csproj ├── Common │ ├── Guard.cs │ ├── IServiceCollection.cs │ └── ServiceCollection.cs ├── Controllers │ └── Controller.cs ├── HTTP │ ├── ContentType.cs │ ├── Cookie.cs │ ├── CookieCollection.cs │ ├── Header.cs │ ├── HeaderCollection.cs │ ├── Method.cs │ ├── Request.cs │ ├── Response.cs │ ├── Session.cs │ └── StatusCode.cs ├── HttpServer.cs ├── Identity │ └── UserIdentity.cs ├── Responses │ ├── BadRequestResponse.cs │ ├── ContentResponse.cs │ ├── FileResponse.cs │ ├── HtmlResponse.cs │ ├── NotFoundResponse.cs │ ├── RedirectResponse.cs │ ├── TextResponse.cs │ ├── UnauthorizedResponse.cs │ └── ViewResponse.cs └── Routing │ ├── IRoutingTable.cs │ ├── RoutingTable.cs │ └── RoutingTableExtension.cs ├── BasicWebServer.sln ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/BasicWebServer.Demo.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Always 15 | 16 | 17 | Always 18 | 19 | 20 | Always 21 | 22 | 23 | Always 24 | 25 | 26 | Always 27 | 28 | 29 | Always 30 | 31 | 32 | Always 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Demo.Models; 2 | using BasicWebServer.Server.Attributes; 3 | using BasicWebServer.Server.Controllers; 4 | using BasicWebServer.Server.HTTP; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Web; 9 | 10 | namespace BasicWebServer.Demo.Controllers 11 | { 12 | public class HomeController : Controller 13 | { 14 | private const string FileName = "content.txt"; 15 | 16 | public HomeController(Request request) 17 | : base(request) 18 | { 19 | 20 | } 21 | 22 | [HttpGet] 23 | public Response Index() => Text("Hello from the server!"); 24 | 25 | public Response Student(string name, int age) => Text($"I'm {name} and I'm {age} years old"); 26 | 27 | public Response Redirect() => Redirect("https://softuni.bg"); 28 | 29 | public Response Html() => View(); 30 | 31 | [HttpPost] 32 | public Response HtmlFormPost() 33 | { 34 | string name = Request.Form["Name"]; 35 | string age = Request.Form["Age"]; 36 | 37 | var model = new FormViewModel() 38 | { 39 | Name = name, 40 | Age = int.Parse(age) 41 | }; 42 | 43 | return View(model); 44 | } 45 | 46 | public Response Test() 47 | { 48 | var model = new List() 49 | { 50 | new(){ Age = 23, Name = "Pesho" }, 51 | new(){ Age = 24, Name = "Gosho" }, 52 | new(){ Age = 23, Name = "Misho" } 53 | }; 54 | 55 | return View(model); 56 | } 57 | 58 | public Response DownloadContent() => File(FileName); 59 | 60 | public Response Cookies() 61 | { 62 | var requestHasCookies = Request.Cookies.Any(c => c.Name != Server.HTTP.Session.SessionCookieName); 63 | var bodyText = ""; 64 | 65 | if (requestHasCookies) 66 | { 67 | var cookieText = new StringBuilder(); 68 | cookieText.AppendLine("

Cookies

"); 69 | 70 | cookieText 71 | .Append(""); 72 | 73 | foreach (var cookie in Request.Cookies) 74 | { 75 | cookieText.Append(""); 76 | cookieText 77 | .Append($""); 78 | cookieText 79 | .Append($""); 80 | cookieText.Append(""); 81 | } 82 | cookieText.Append("
NameValue
{HttpUtility.HtmlEncode(cookie.Name)}{HttpUtility.HtmlEncode(cookie.Value)}
"); 83 | 84 | bodyText = cookieText.ToString(); 85 | 86 | return Html(bodyText); 87 | } 88 | else 89 | { 90 | bodyText = "

Cookies set!

"; 91 | } 92 | 93 | var cookies = new CookieCollection(); 94 | 95 | if (!requestHasCookies) 96 | { 97 | cookies.Add("My-Cookie", "My-Value"); 98 | cookies.Add("My-Second-Cookie", "My-Second-Value"); 99 | } 100 | 101 | return Html(bodyText, cookies); 102 | } 103 | 104 | public Response Session() 105 | { 106 | var sessionExists = Request.Session 107 | .ContainsKey(Server.HTTP.Session.SessionCurrentDateKey); 108 | 109 | var bodyText = ""; 110 | 111 | if (sessionExists) 112 | { 113 | var currentDate = Request.Session[Server.HTTP.Session.SessionCurrentDateKey]; 114 | bodyText = $"Stored date: {currentDate}!"; 115 | } 116 | else 117 | { 118 | bodyText = "Current date stored!"; 119 | } 120 | 121 | return Text(bodyText); 122 | } 123 | 124 | public Response Content() => View(); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Controllers/UserController.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Demo.Services; 2 | using BasicWebServer.Server.Attributes; 3 | using BasicWebServer.Server.Controllers; 4 | using BasicWebServer.Server.HTTP; 5 | using System; 6 | 7 | namespace BasicWebServer.Demo.Controllers 8 | { 9 | public class UserController : Controller 10 | { 11 | private readonly UserService userService; 12 | 13 | public UserController(Request request, UserService _userService) 14 | : base(request) 15 | { 16 | userService = _userService; 17 | } 18 | 19 | [HttpPost] 20 | public Response LoginUser() 21 | { 22 | Request.Session.Clear(); 23 | 24 | var bodyText = ""; 25 | 26 | var username = Request.Form["Username"]; 27 | var password = Request.Form["Password"]; 28 | 29 | if (userService.IsLoginCorrect(username, password)) 30 | { 31 | SignIn(Guid.NewGuid().ToString()); 32 | 33 | CookieCollection cookies = new CookieCollection(); 34 | cookies.Add(Session.SessionCookieName, 35 | Request.Session.Id); 36 | 37 | bodyText = "

Logged successfully!

"; 38 | 39 | return Html(bodyText, cookies); 40 | } 41 | 42 | return Redirect("/Login"); 43 | } 44 | 45 | [Authorize] 46 | public Response GetUserData() 47 | { 48 | return Html($"

Currently logged-in user is with id '{User.Id}'

"); 49 | } 50 | 51 | public Response Logout() 52 | { 53 | SignOut(); 54 | 55 | return Html("

Logged out successfully!

"); 56 | } 57 | 58 | public Response Login() => View(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Models/FormViewModel.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Demo.Models 2 | { 3 | public class FormViewModel 4 | { 5 | public string Name { get; set; } 6 | 7 | public int Age { get; set; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Services/UserService.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Demo.Services 2 | { 3 | public class UserService 4 | { 5 | private const string Username = "user"; 6 | 7 | private const string Password = "user123"; 8 | 9 | public bool IsLoginCorrect(string username, string password) 10 | => username == Username && password == Password; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Startup.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Demo.Services; 2 | using BasicWebServer.Server; 3 | using BasicWebServer.Server.Routing; 4 | using System.Threading.Tasks; 5 | 6 | namespace BasicWebServer.Demo 7 | { 8 | public class Startup 9 | { 10 | public static async Task Main() 11 | { 12 | var server = new HttpServer(routes => routes 13 | .MapControllers() 14 | .MapStaticFiles()); 15 | 16 | server.ServiceCollection 17 | .Add(); 18 | 19 | await server.Start(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/Home/Content.cshtml: -------------------------------------------------------------------------------- 1 | 
2 | 3 |
-------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/Home/Html.cshtml: -------------------------------------------------------------------------------- 1 | 
2 | Name: 3 | Age: 4 | 5 |
-------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/Home/HtmlFormPost.cshtml: -------------------------------------------------------------------------------- 1 | 

Hello from {{Name}}! I am {{Age}} years old!

-------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/Home/Test.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | {{foreach}} 10 | { 11 | 12 | 13 | 14 | 15 | } 16 | 17 |
NameAge
{{Name}}{{Age}}
-------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Demo Web Application 7 | 8 | 9 | {{RenderBody}} 10 | 11 | -------------------------------------------------------------------------------- /BasicWebServer.Demo/Views/User/Login.cshtml: -------------------------------------------------------------------------------- 1 | 
2 | Username: 3 | Password: 4 | 5 |
-------------------------------------------------------------------------------- /BasicWebServer.Demo/content.txt: -------------------------------------------------------------------------------- 1 | This is my awsome file 2 | 3 | And I edited it :) -------------------------------------------------------------------------------- /BasicWebServer.Server/Attributes/AuthorizeAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BasicWebServer.Server.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] 6 | public class AuthorizeAttribute : Attribute 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Attributes/HttpGetAttribute.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Attributes 4 | { 5 | public class HttpGetAttribute : HttpMethodAttribute 6 | { 7 | public HttpGetAttribute() : base(Method.Get) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Attributes/HttpMethodAttribute.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | using System; 3 | 4 | namespace BasicWebServer.Server.Attributes 5 | { 6 | [AttributeUsage(AttributeTargets.Method)] 7 | public abstract class HttpMethodAttribute : Attribute 8 | { 9 | public Method HttpMethod { get; } 10 | 11 | protected HttpMethodAttribute(Method httpMethod) 12 | => HttpMethod = httpMethod; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Attributes/HttpPostAttribute.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Attributes 4 | { 5 | public class HttpPostAttribute : HttpMethodAttribute 6 | { 7 | public HttpPostAttribute() : base(Method.Post) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BasicWebServer.Server/BasicWebServer.Server.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Common/Guard.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace BasicWebServer.Server.Common 5 | { 6 | public static class Guard 7 | { 8 | public static void AgainstNull(object value, string name = null) 9 | { 10 | if (value == null) 11 | { 12 | name ??= "Value"; 13 | 14 | throw new ArgumentException($"{name} cannot be null."); 15 | } 16 | } 17 | 18 | public static void AgainstDuplicatedKey(IDictionary dictionary, T key, string name) 19 | { 20 | if (dictionary.ContainsKey(key)) 21 | { 22 | throw new ArgumentException($"{name} already contains key {key.ToString()}"); 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Common/IServiceCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace BasicWebServer.Server.Common 4 | { 5 | public interface IServiceCollection 6 | { 7 | IServiceCollection Add() 8 | where TService : class 9 | where TImplementation : TService; 10 | 11 | IServiceCollection Add() 12 | where TService : class; 13 | 14 | TService Get() 15 | where TService: class; 16 | 17 | object CreateInstance(Type serviceType); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Common/ServiceCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace BasicWebServer.Server.Common 8 | { 9 | public class ServiceCollection : IServiceCollection 10 | { 11 | private readonly Dictionary services; 12 | 13 | public ServiceCollection() 14 | { 15 | services = new Dictionary(); 16 | } 17 | 18 | public IServiceCollection Add() 19 | where TService : class 20 | where TImplementation : TService 21 | { 22 | services[typeof(TService)] = typeof(TImplementation); 23 | 24 | return this; 25 | } 26 | 27 | public IServiceCollection Add() where TService : class 28 | { 29 | return Add(); 30 | } 31 | 32 | public object CreateInstance(Type serviceType) 33 | { 34 | if (services.ContainsKey(serviceType)) 35 | { 36 | serviceType = services[serviceType]; 37 | } 38 | else if (serviceType.IsInterface) 39 | { 40 | throw new InvalidOperationException($"Service {serviceType.FullName} is not registered"); 41 | } 42 | 43 | var constructors = serviceType.GetConstructors(); 44 | 45 | if (constructors.Length > 1) 46 | { 47 | throw new InvalidOperationException("Multiple constructors are not supported"); 48 | } 49 | 50 | var constructor = constructors.First(); 51 | var parameters = constructor.GetParameters(); 52 | var parameterValues = new object[parameters.Length]; 53 | 54 | for (int i = 0; i < parameterValues.Length; i++) 55 | { 56 | var parameterType = parameters[i].ParameterType; 57 | var parameterValue = CreateInstance(parameterType); 58 | 59 | parameterValues[i] = parameterValue; 60 | } 61 | 62 | return constructor.Invoke(parameterValues); 63 | } 64 | 65 | public TService Get() where TService : class 66 | { 67 | var serviceType = typeof(TService); 68 | 69 | if (!services.ContainsKey(serviceType)) 70 | { 71 | return null; 72 | } 73 | 74 | var service = services[serviceType]; 75 | 76 | return (TService)CreateInstance(service); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Controllers/Controller.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | using BasicWebServer.Server.Identity; 3 | using BasicWebServer.Server.Responses; 4 | using System.Runtime.CompilerServices; 5 | 6 | namespace BasicWebServer.Server.Controllers 7 | { 8 | public class Controller 9 | { 10 | protected Request Request { get; set; } 11 | 12 | private UserIdentity userIdentity; 13 | 14 | public Controller(Request request) 15 | { 16 | Request = request; 17 | } 18 | 19 | protected UserIdentity User 20 | { 21 | get 22 | { 23 | if (this.userIdentity == null) 24 | { 25 | this.userIdentity = this.Request.Session.ContainsKey(Session.SessionUserKey) 26 | ? new UserIdentity { Id = this.Request.Session[Session.SessionUserKey] } 27 | : new(); 28 | } 29 | 30 | return this.userIdentity; 31 | } 32 | } 33 | 34 | protected void SignIn(string userId) 35 | { 36 | this.Request.Session[Session.SessionUserKey] = userId; 37 | this.userIdentity = new UserIdentity { Id = userId }; 38 | } 39 | 40 | protected void SignOut() 41 | { 42 | this.Request.Session.Clear(); 43 | this.userIdentity = new(); 44 | } 45 | 46 | protected Response Text(string text) => new TextResponse(text); 47 | protected Response Html(string text) => new HtmlResponse(text); 48 | protected Response Html(string html, CookieCollection cookies) 49 | { 50 | var response = new HtmlResponse(html); 51 | 52 | if (cookies != null) 53 | { 54 | foreach (var cookie in cookies) 55 | { 56 | response.Cookies.Add(cookie.Name, cookie.Value); 57 | } 58 | } 59 | 60 | return response; 61 | } 62 | 63 | protected Response BadRequest() => new BadRequestResponse(); 64 | protected Response Unauthorized() => new UnauthorizedResponse(); 65 | protected Response NotFound() => new NotFoundResponse(); 66 | protected Response Redirect(string location) => new RedirectResponse(location); 67 | protected Response File(string fileName) => new FileResponse(fileName); 68 | protected Response View([CallerMemberName] string viewName = "") 69 | => new ViewResponse(viewName, GetControllerName()); 70 | protected Response View(object model, [CallerMemberName] string viewName = "") 71 | => new ViewResponse(viewName, GetControllerName(), model); 72 | 73 | private string GetControllerName() 74 | => this.GetType().Name 75 | .Replace(nameof(Controller), string.Empty); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/ContentType.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Server.HTTP 2 | { 3 | public class ContentType 4 | { 5 | public const string PlainText = "text/plain; charset=UTF-8"; 6 | public const string Html = "text/html; charset=UTF-8"; 7 | public const string FormUrlEncoded = "application/x-www-form-urlencoded"; 8 | public const string FileContent = "application/octet-stream"; 9 | 10 | public static string GetByFileExtension(string fileExtension) 11 | => fileExtension switch 12 | { 13 | "css" => "text/css", 14 | "js" => "application/javascript", 15 | "jpg" or "jpeg" => "image/jpeg", 16 | "png" => "image/png", 17 | _ => PlainText 18 | }; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Cookie.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.Common; 2 | 3 | namespace BasicWebServer.Server.HTTP 4 | { 5 | public class Cookie 6 | { 7 | public Cookie(string name, string value) 8 | { 9 | Guard.AgainstNull(name, nameof(name)); 10 | Guard.AgainstNull(value, nameof(value)); 11 | 12 | this.Name = name; 13 | this.Value = value; 14 | } 15 | 16 | public string Name { get; init; } 17 | 18 | public string Value { get; init; } 19 | 20 | public override string ToString() 21 | => $"{this.Name}={this.Value}"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/CookieCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | 4 | namespace BasicWebServer.Server.HTTP 5 | { 6 | public class CookieCollection : IEnumerable 7 | { 8 | private readonly Dictionary cookies; 9 | 10 | public CookieCollection() 11 | => this.cookies = new Dictionary(); 12 | 13 | public string this[string name] 14 | => this.cookies[name].Value; 15 | 16 | public void Add(string name, string value) 17 | => this.cookies[name] = new Cookie(name, value); 18 | 19 | public bool Contains(string name) 20 | => this.cookies.ContainsKey(name); 21 | 22 | public IEnumerator GetEnumerator() 23 | => this.cookies.Values.GetEnumerator(); 24 | 25 | IEnumerator IEnumerable.GetEnumerator() 26 | => this.GetEnumerator(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Header.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.Common; 2 | 3 | namespace BasicWebServer.Server.HTTP 4 | { 5 | public class Header 6 | { 7 | public const string ContentType = "Content-Type"; 8 | public const string ContentLength = "Content-Length"; 9 | public const string ContentDisposition = "Content-Disposition"; 10 | public const string Cookie = "Cookie"; 11 | public const string Date = "Date"; 12 | public const string Location = "Location"; 13 | public const string Server = "Server"; 14 | public const string SetCookie = "Set-Cookie"; 15 | 16 | public Header(string name, string value) 17 | { 18 | Guard.AgainstNull(name, nameof(name)); 19 | Guard.AgainstNull(value, nameof(value)); 20 | 21 | this.Name = name; 22 | this.Value = value; 23 | } 24 | 25 | public string Name { get; init; } 26 | 27 | public string Value { get; set; } 28 | 29 | public override string ToString() 30 | => $"{this.Name}: {this.Value}"; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/HeaderCollection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | 4 | namespace BasicWebServer.Server.HTTP 5 | { 6 | public class HeaderCollection : IEnumerable
7 | { 8 | private readonly Dictionary headers; 9 | 10 | public HeaderCollection() 11 | => this.headers = new Dictionary(); 12 | 13 | public string this[string name] 14 | => this.headers[name].Value; 15 | 16 | public int Count => this.headers.Count; 17 | 18 | public bool Contains(string name) 19 | => this.headers.ContainsKey(name); 20 | 21 | public void Add(string name, string value) 22 | => this.headers[name] = new Header(name, value); 23 | 24 | public IEnumerator
GetEnumerator() 25 | => this.headers.Values.GetEnumerator(); 26 | 27 | IEnumerator IEnumerable.GetEnumerator() 28 | => this.GetEnumerator(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Method.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Server.HTTP 2 | { 3 | public enum Method 4 | { 5 | Get = 1, 6 | Post = 2, 7 | Put = 3, 8 | Delete = 4 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Request.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Web; 3 | using System.Linq; 4 | using System.Collections.Generic; 5 | using BasicWebServer.Server.Common; 6 | 7 | namespace BasicWebServer.Server.HTTP 8 | { 9 | public class Request 10 | { 11 | private static Dictionary Sessions = new(); 12 | 13 | public Method Method { get; private set; } 14 | 15 | public string Url { get; private set; } 16 | 17 | public HeaderCollection Headers { get; private set; } 18 | 19 | public CookieCollection Cookies { get; private set; } 20 | 21 | public string Body { get; private set; } 22 | 23 | public Session Session { get; private set; } 24 | 25 | public IReadOnlyDictionary Form { get; private set; } 26 | 27 | public IReadOnlyDictionary Query { get; private set; } 28 | 29 | public static IServiceCollection ServiceCollection { get; private set; } 30 | 31 | public static Request Parse(string request, IServiceCollection serviceCollection) 32 | { 33 | ServiceCollection = serviceCollection; 34 | 35 | var lines = request.Split("\r\n"); 36 | 37 | var startLine = lines.First().Split(" "); 38 | 39 | var method = ParseMethod(startLine[0]); 40 | (string url, Dictionary query) = ParseUrl(startLine[1]); 41 | 42 | var headers = ParseHeaders(lines.Skip(1)); 43 | 44 | var cookies = ParseCookies(headers); 45 | 46 | var session = GetSession(cookies); 47 | 48 | var bodyLines = lines.Skip(headers.Count + 2).ToArray(); 49 | 50 | var body = string.Join("\r\n", bodyLines); 51 | 52 | var form = ParseForm(headers, body); 53 | 54 | return new Request 55 | { 56 | Method = method, 57 | Url = url, 58 | Headers = headers, 59 | Cookies = cookies, 60 | Body = body, 61 | Session = session, 62 | Form = form, 63 | Query = query 64 | }; 65 | } 66 | 67 | private static (string url, Dictionary query) ParseUrl(string queryString) 68 | { 69 | string url = String.Empty; 70 | Dictionary query = new Dictionary(); 71 | var parts = queryString.Split("?",2); 72 | 73 | if (parts.Length > 1) 74 | { 75 | var queryParams = parts[1].Split("&"); 76 | 77 | foreach (var pair in queryParams) 78 | { 79 | var param = pair.Split('='); 80 | 81 | if (param.Length == 2) 82 | { 83 | query.Add(param[0], param[1]); 84 | } 85 | } 86 | } 87 | 88 | url = parts[0]; 89 | 90 | return (url, query); 91 | } 92 | 93 | private static Method ParseMethod(string method) 94 | { 95 | try 96 | { 97 | return (Method)Enum.Parse(typeof(Method), method, true); 98 | } 99 | catch (Exception) 100 | { 101 | throw new InvalidOperationException($"Method '{method}' is not supported"); 102 | } 103 | } 104 | 105 | private static HeaderCollection ParseHeaders(IEnumerable headerLines) 106 | { 107 | var headerCollection = new HeaderCollection(); 108 | 109 | foreach (var headerLine in headerLines) 110 | { 111 | if (headerLine == string.Empty) 112 | { 113 | break; 114 | } 115 | 116 | var headerParts = headerLine.Split(":", 2); 117 | 118 | if (headerParts.Length != 2) 119 | { 120 | throw new InvalidOperationException("Request is not valid."); 121 | } 122 | 123 | var headerName = headerParts[0]; 124 | var headerValue = headerParts[1].Trim(); 125 | 126 | headerCollection.Add(headerName, headerValue); 127 | } 128 | 129 | return headerCollection; 130 | } 131 | 132 | private static CookieCollection ParseCookies(HeaderCollection headers) 133 | { 134 | var cookieCollection = new CookieCollection(); 135 | 136 | if (headers.Contains(Header.Cookie)) 137 | { 138 | var cookieHeader = headers[Header.Cookie]; 139 | 140 | var allCookies = cookieHeader.Split(';'); 141 | 142 | foreach (var cookieText in allCookies) 143 | { 144 | var cookieParts = cookieText.Split('='); 145 | 146 | var cookieName = cookieParts[0].Trim(); 147 | var cookieValue = cookieParts[1].Trim(); 148 | 149 | cookieCollection.Add(cookieName, cookieValue); 150 | } 151 | } 152 | 153 | return cookieCollection; 154 | } 155 | 156 | private static Session GetSession(CookieCollection cookies) 157 | { 158 | var sessionId = cookies.Contains(Session.SessionCookieName) 159 | ? cookies[Session.SessionCookieName] 160 | : Guid.NewGuid().ToString(); 161 | 162 | if (!Sessions.ContainsKey(sessionId)) 163 | { 164 | Sessions[sessionId] = new Session(sessionId); 165 | } 166 | 167 | return Sessions[sessionId]; 168 | } 169 | 170 | private static Dictionary ParseForm(HeaderCollection headers, string body) 171 | { 172 | var formCollection = new Dictionary(); 173 | 174 | if (headers.Contains(Header.ContentType) 175 | && headers[Header.ContentType] == ContentType.FormUrlEncoded) 176 | { 177 | var parsedResult = ParseFormData(body); 178 | 179 | foreach (var (name, value) in parsedResult) 180 | { 181 | formCollection.Add(name, value); 182 | } 183 | } 184 | 185 | return formCollection; 186 | } 187 | 188 | private static Dictionary ParseFormData(string bodyLines) 189 | => HttpUtility.UrlDecode(bodyLines) 190 | .Split('&') 191 | .Select(part => part.Split('=')) 192 | .Where(part => part.Length == 2) 193 | .ToDictionary( 194 | part => part[0], 195 | part => part[1], 196 | StringComparer.InvariantCultureIgnoreCase); 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Response.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | 4 | namespace BasicWebServer.Server.HTTP 5 | { 6 | public class Response 7 | { 8 | public Response(StatusCode statusCode) 9 | { 10 | this.StatusCode = statusCode; 11 | 12 | this.Headers.Add(Header.Server, "My Web Server"); 13 | this.Headers.Add(Header.Date, $"{DateTime.UtcNow:r}"); 14 | } 15 | 16 | public StatusCode StatusCode { get; init; } 17 | 18 | public HeaderCollection Headers { get; } = new HeaderCollection(); 19 | 20 | public CookieCollection Cookies { get; } = new CookieCollection(); 21 | 22 | public string Body { get; set; } 23 | 24 | public byte[] FileContent { get; set; } 25 | 26 | public override string ToString() 27 | { 28 | var result = new StringBuilder(); 29 | 30 | result.AppendLine($"HTTP/1.1 {(int)this.StatusCode} {this.StatusCode}"); 31 | 32 | foreach (var header in this.Headers) 33 | { 34 | result.AppendLine(header.ToString()); 35 | } 36 | 37 | foreach (var cookie in this.Cookies) 38 | { 39 | result.AppendLine($"{Header.SetCookie}: {cookie}"); 40 | } 41 | 42 | result.AppendLine(); 43 | 44 | if (!string.IsNullOrEmpty(this.Body)) 45 | { 46 | result.Append(this.Body); 47 | } 48 | 49 | return result.ToString(); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/Session.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using BasicWebServer.Server.Common; 3 | 4 | namespace BasicWebServer.Server.HTTP 5 | { 6 | public class Session 7 | { 8 | public const string SessionCookieName = "MyWebServerSID"; 9 | 10 | public const string SessionCurrentDateKey = "CurrentDate"; 11 | 12 | public const string SessionUserKey = "AuthenticatedUserId"; 13 | 14 | private Dictionary data; 15 | 16 | public Session(string id) 17 | { 18 | Guard.AgainstNull(id, nameof(id)); 19 | 20 | this.Id = id; 21 | 22 | this.data = new Dictionary(); 23 | } 24 | 25 | public string Id { get; init; } 26 | 27 | public string this[string key] 28 | { 29 | get => this.data[key]; 30 | set => this.data[key] = value; 31 | } 32 | 33 | public bool ContainsKey(string key) 34 | => this.data.ContainsKey(key); 35 | 36 | public void Clear() 37 | => this.data.Clear(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HTTP/StatusCode.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Server.HTTP 2 | { 3 | public enum StatusCode 4 | { 5 | OK = 200, 6 | Found = 302, 7 | BadRequest = 400, 8 | Unauthorized = 401, 9 | NotFound = 404 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BasicWebServer.Server/HttpServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Text; 4 | using System.Net.Sockets; 5 | using System.Threading.Tasks; 6 | using BasicWebServer.Server.HTTP; 7 | using BasicWebServer.Server.Routing; 8 | using System.Linq; 9 | using BasicWebServer.Server.Common; 10 | 11 | namespace BasicWebServer.Server 12 | { 13 | public class HttpServer 14 | { 15 | private readonly IPAddress ipAddress; 16 | private readonly int port; 17 | private readonly TcpListener serverListener; 18 | 19 | private readonly RoutingTable routingTable; 20 | 21 | public readonly IServiceCollection ServiceCollection; 22 | 23 | public HttpServer(string ipAddress, int port, Action routingTableConfiguration) 24 | { 25 | this.ipAddress = IPAddress.Parse(ipAddress); 26 | this.port = port; 27 | 28 | this.serverListener = new TcpListener(this.ipAddress, port); 29 | 30 | routingTableConfiguration(this.routingTable = new RoutingTable()); 31 | ServiceCollection = new ServiceCollection(); 32 | } 33 | 34 | public HttpServer(int port, Action routingTable) 35 | : this("127.0.0.1", port, routingTable) 36 | { 37 | } 38 | 39 | public HttpServer(Action routingTable) 40 | : this(8080, routingTable) 41 | { 42 | } 43 | 44 | public async Task Start() 45 | { 46 | this.serverListener.Start(); 47 | 48 | Console.WriteLine($"Server started on port {port}."); 49 | Console.WriteLine("Listening for requests..."); 50 | 51 | while (true) 52 | { 53 | var connection = await serverListener.AcceptTcpClientAsync(); 54 | 55 | _ = Task.Run(async () => 56 | { 57 | var networkStream = connection.GetStream(); 58 | 59 | var requestText = await this.ReadRequest(networkStream); 60 | 61 | Console.WriteLine(requestText); 62 | 63 | var request = Request.Parse(requestText, ServiceCollection); 64 | 65 | var response = this.routingTable.MatchRequest(request); 66 | 67 | AddSession(request, response); 68 | 69 | await WriteResponse(networkStream, response); 70 | 71 | connection.Close(); 72 | }); 73 | } 74 | } 75 | 76 | private async Task ReadRequest(NetworkStream networkStream) 77 | { 78 | var bufferLength = 1024; 79 | var buffer = new byte[bufferLength]; 80 | 81 | var totalBytes = 0; 82 | 83 | var requestBuilder = new StringBuilder(); 84 | 85 | do 86 | { 87 | var bytesRead = await networkStream.ReadAsync(buffer, 0, bufferLength); 88 | 89 | totalBytes += bytesRead; 90 | 91 | if (totalBytes > 10 * 1024) 92 | { 93 | throw new InvalidOperationException("Request is too large."); 94 | } 95 | 96 | requestBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); 97 | } 98 | while (networkStream.DataAvailable); // May not run correctly over the Internet 99 | 100 | return requestBuilder.ToString(); 101 | } 102 | 103 | private async Task WriteResponse(NetworkStream networkStream, Response response) 104 | { 105 | var resposeBytes = Encoding.UTF8.GetBytes(response.ToString()); 106 | 107 | if (response.FileContent != null) 108 | { 109 | resposeBytes = resposeBytes 110 | .Concat(response.FileContent) 111 | .ToArray(); 112 | } 113 | 114 | await networkStream.WriteAsync(resposeBytes); 115 | } 116 | 117 | private static void AddSession(Request request, Response response) 118 | { 119 | var sessionExists = request.Session.ContainsKey(Session.SessionCurrentDateKey); 120 | 121 | if (!sessionExists) 122 | { 123 | request.Session[Session.SessionCurrentDateKey] = DateTime.Now.ToString(); 124 | response.Cookies.Add(Session.SessionCookieName, request.Session.Id); 125 | } 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Identity/UserIdentity.cs: -------------------------------------------------------------------------------- 1 | namespace BasicWebServer.Server.Identity 2 | { 3 | public class UserIdentity 4 | { 5 | public string Id { get; init; } 6 | 7 | public bool IsAuthenticated => this.Id != null; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/BadRequestResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Responses 4 | { 5 | public class BadRequestResponse : Response 6 | { 7 | public BadRequestResponse() 8 | : base(StatusCode.BadRequest) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/ContentResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.Common; 2 | using BasicWebServer.Server.HTTP; 3 | using System.Text; 4 | 5 | namespace BasicWebServer.Server.Responses 6 | { 7 | public class ContentResponse : Response 8 | { 9 | public ContentResponse(string content, string contentType) 10 | : base(StatusCode.OK) 11 | { 12 | Guard.AgainstNull(content); 13 | Guard.AgainstNull(contentType); 14 | 15 | this.Headers.Add(Header.ContentType, contentType); 16 | 17 | this.Body = content; 18 | } 19 | 20 | public override string ToString() 21 | { 22 | if (this.Body != null) 23 | { 24 | var contentLength = Encoding.UTF8.GetByteCount(this.Body).ToString(); 25 | this.Headers.Add(Header.ContentLength, contentLength); 26 | } 27 | 28 | return base.ToString(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/FileResponse.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using BasicWebServer.Server.HTTP; 3 | 4 | namespace BasicWebServer.Server.Responses 5 | { 6 | public class FileResponse : Response 7 | { 8 | public string FileName { get; init; } 9 | 10 | public FileResponse(string fileName) 11 | : base(StatusCode.OK) 12 | { 13 | this.FileName = fileName; 14 | 15 | this.Headers.Add(Header.ContentType, ContentType.FileContent); 16 | } 17 | 18 | public override string ToString() 19 | { 20 | if (File.Exists(this.FileName)) 21 | { 22 | this.Body = string.Empty; 23 | FileContent = File.ReadAllBytes(this.FileName); 24 | 25 | var fileBytesCount = new FileInfo(this.FileName).Length; 26 | this.Headers.Add(Header.ContentLength, fileBytesCount.ToString()); 27 | 28 | this.Headers.Add(Header.ContentDisposition, 29 | $"attachment; filename=\"{this.FileName}\""); 30 | } 31 | 32 | return base.ToString(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/HtmlResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using BasicWebServer.Server.HTTP; 3 | 4 | namespace BasicWebServer.Server.Responses 5 | { 6 | public class HtmlResponse : ContentResponse 7 | { 8 | public HtmlResponse(string text) 9 | : base(text, ContentType.Html) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/NotFoundResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Responses 4 | { 5 | public class NotFoundResponse : Response 6 | { 7 | public NotFoundResponse() 8 | : base(StatusCode.NotFound) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/RedirectResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Responses 4 | { 5 | public class RedirectResponse : Response 6 | { 7 | public RedirectResponse(string location) 8 | : base(StatusCode.Found) 9 | { 10 | this.Headers.Add(Header.Location, location); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/TextResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Responses 4 | { 5 | public class TextResponse : ContentResponse 6 | { 7 | public TextResponse(string text) 8 | : base(text, ContentType.PlainText) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/UnauthorizedResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | 3 | namespace BasicWebServer.Server.Responses 4 | { 5 | public class UnauthorizedResponse : Response 6 | { 7 | public UnauthorizedResponse() 8 | : base(StatusCode.Unauthorized) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Responses/ViewResponse.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | using System; 3 | using System.Collections; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace BasicWebServer.Server.Responses 9 | { 10 | public class ViewResponse : ContentResponse 11 | { 12 | private const char PathSeparator = '/'; 13 | 14 | public ViewResponse(string viewName, string controllerName, object model = null) 15 | : base(string.Empty, ContentType.Html) 16 | { 17 | if (!viewName.Contains(PathSeparator)) 18 | { 19 | viewName = controllerName + PathSeparator + viewName; 20 | } 21 | 22 | var viewPath = Path 23 | .GetFullPath($"./Views/{viewName.TrimStart(PathSeparator)}.cshtml"); 24 | var viewContent = File.ReadAllText(viewPath); 25 | 26 | var (layoutPath, layoutExists) = FindLayout(); 27 | 28 | if (layoutExists) 29 | { 30 | var layoutContent = File.ReadAllText(layoutPath); 31 | 32 | viewContent = layoutContent.Replace("{{RenderBody}}", viewContent); 33 | } 34 | 35 | if (model != null) 36 | { 37 | viewContent = EvaluateConditions(viewContent, model); 38 | 39 | if (model is IEnumerable) 40 | { 41 | viewContent = PopulateEnumerableModel(viewContent, model); 42 | } 43 | else 44 | { 45 | viewContent = PopulateModel(viewContent, model); 46 | } 47 | } 48 | 49 | Body = viewContent; 50 | } 51 | 52 | private string PopulateEnumerableModel(string viewContent, object model) 53 | { 54 | var result = new StringBuilder(); 55 | 56 | var lines = viewContent 57 | .Split(Environment.NewLine) 58 | .Select(line => line.Trim()); 59 | 60 | var inLoop = false; 61 | StringBuilder loopContent = null; 62 | 63 | foreach (var line in lines) 64 | { 65 | if (line.StartsWith("{{foreach}}")) 66 | { 67 | inLoop = true; 68 | 69 | continue; 70 | } 71 | 72 | if (inLoop) 73 | { 74 | if (line.StartsWith("{")) 75 | { 76 | loopContent = new StringBuilder(); 77 | } 78 | else if (line.StartsWith("}")) 79 | { 80 | var loopTemplate = loopContent.ToString(); 81 | 82 | foreach (var item in (IEnumerable)model) 83 | { 84 | var loopResult = PopulateModel(loopTemplate, item); 85 | 86 | result.AppendLine(loopResult); 87 | } 88 | 89 | inLoop = false; 90 | } 91 | else 92 | { 93 | loopContent.AppendLine(line); 94 | } 95 | 96 | continue; 97 | } 98 | 99 | result.AppendLine(line); 100 | } 101 | 102 | return result.ToString(); 103 | } 104 | 105 | private string EvaluateConditions(string viewContent, object model) 106 | { 107 | var result = new StringBuilder(); 108 | 109 | var lines = viewContent 110 | .Split(Environment.NewLine) 111 | .Select(line => line.Trim()); 112 | 113 | var inCondition = false; 114 | var waitingForElse = false; 115 | var inElse = false; 116 | string conditionPropertyName = string.Empty; 117 | 118 | StringBuilder ifContent = null; 119 | StringBuilder elseContent = null; 120 | 121 | foreach (var line in lines) 122 | { 123 | if (line.StartsWith("{{if(")) 124 | { 125 | int start = line.IndexOf('(') + 1; 126 | int end = line.IndexOf(')'); 127 | conditionPropertyName = line.Substring(start, end - start)?.Trim(); 128 | inCondition = true; 129 | inElse = false; 130 | waitingForElse = false; 131 | 132 | continue; 133 | } 134 | 135 | if (inCondition) 136 | { 137 | if (waitingForElse && line.StartsWith("{{else}}")) 138 | { 139 | inElse = true; 140 | inCondition = false; 141 | waitingForElse = false; 142 | 143 | continue; 144 | } 145 | else if (waitingForElse) 146 | { 147 | inElse = false; 148 | inCondition = false; 149 | waitingForElse = false; 150 | 151 | string conditionResult = GetConditionContent(ifContent, elseContent, model, conditionPropertyName); 152 | 153 | if (!string.IsNullOrWhiteSpace(conditionResult)) 154 | { 155 | result.AppendLine(conditionResult); 156 | } 157 | 158 | result.AppendLine(line); 159 | 160 | continue; 161 | } 162 | 163 | if (line.StartsWith("{")) 164 | { 165 | ifContent = new StringBuilder(); 166 | } 167 | else if (line.StartsWith("}")) 168 | { 169 | waitingForElse = true; 170 | } 171 | else 172 | { 173 | ifContent.AppendLine(line); 174 | } 175 | 176 | continue; 177 | } 178 | 179 | if (inElse) 180 | { 181 | if (line.StartsWith("{")) 182 | { 183 | elseContent = new StringBuilder(); 184 | } 185 | else if (line.StartsWith("}")) 186 | { 187 | inElse = false; 188 | string conditionResult = GetConditionContent(ifContent, elseContent, model, conditionPropertyName); 189 | 190 | if (!string.IsNullOrWhiteSpace(conditionResult)) 191 | { 192 | result.AppendLine(conditionResult); 193 | } 194 | } 195 | else 196 | { 197 | elseContent.AppendLine(line); 198 | } 199 | 200 | continue; 201 | } 202 | 203 | result.AppendLine(line); 204 | } 205 | 206 | return result.ToString(); 207 | } 208 | 209 | private string GetConditionContent(StringBuilder ifContent, StringBuilder elseContent, object model, string conditionPropertyName) 210 | { 211 | var prop = model 212 | .GetType() 213 | .GetProperty(conditionPropertyName); 214 | 215 | if (prop != null) 216 | { 217 | bool? conditionResult = prop.GetValue(model) as bool?; 218 | 219 | if (conditionResult == true && ifContent != null) 220 | { 221 | return ifContent.ToString(); 222 | } 223 | else if (conditionResult == false && elseContent != null) 224 | { 225 | return elseContent.ToString(); 226 | } 227 | } 228 | 229 | return null; 230 | } 231 | 232 | private string PopulateModel(string viewContent, object model) 233 | { 234 | var data = model 235 | .GetType() 236 | .GetProperties() 237 | .Select(p => new 238 | { 239 | p.Name, 240 | Value = p.GetValue(model) 241 | }); 242 | 243 | foreach (var item in data) 244 | { 245 | if (item.Value is IEnumerable && item.Value is not string) 246 | { 247 | viewContent = PopulateEnumerableModel(viewContent, item.Value); 248 | 249 | continue; 250 | } 251 | 252 | const string openingBrackets = "{{"; 253 | const string closingBrackets = "}}"; 254 | 255 | viewContent = viewContent.Replace($"{openingBrackets}{item.Name}{closingBrackets}", item.Value.ToString()); 256 | } 257 | 258 | return viewContent; 259 | } 260 | 261 | private (string, bool) FindLayout() 262 | { 263 | string layoutPath = null; 264 | bool exists = false; 265 | 266 | layoutPath = Path.GetFullPath("./Views/Layout.cshtml"); 267 | 268 | if (File.Exists(layoutPath)) 269 | { 270 | exists = true; 271 | } 272 | else 273 | { 274 | layoutPath = Path.GetFullPath("./Views/Shared/_Layout.cshtml"); 275 | 276 | if (File.Exists(layoutPath)) 277 | { 278 | exists = true; 279 | } 280 | } 281 | 282 | return (layoutPath, exists); 283 | } 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Routing/IRoutingTable.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.HTTP; 2 | using System; 3 | 4 | namespace BasicWebServer.Server.Routing 5 | { 6 | public interface IRoutingTable 7 | { 8 | IRoutingTable Map(Method method, string path, Func responseFunction); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Routing/RoutingTable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using BasicWebServer.Server.HTTP; 4 | using BasicWebServer.Server.Common; 5 | using BasicWebServer.Server.Responses; 6 | 7 | namespace BasicWebServer.Server.Routing 8 | { 9 | public class RoutingTable : IRoutingTable 10 | { 11 | private readonly Dictionary>> routes; 12 | 13 | public RoutingTable() => this.routes = new() 14 | { 15 | [Method.Get] = new(StringComparer.InvariantCultureIgnoreCase), 16 | [Method.Post] = new(StringComparer.InvariantCultureIgnoreCase), 17 | [Method.Put] = new(StringComparer.InvariantCultureIgnoreCase), 18 | [Method.Delete] = new(StringComparer.InvariantCultureIgnoreCase) 19 | }; 20 | 21 | 22 | public IRoutingTable Map( 23 | Method method, 24 | string path, 25 | Func responseFunction) 26 | { 27 | Guard.AgainstNull(path, nameof(path)); 28 | Guard.AgainstNull(responseFunction, nameof(responseFunction)); 29 | 30 | switch (method) 31 | { 32 | case Method.Get: 33 | return MapGet(path, responseFunction); 34 | case Method.Post: 35 | return MapPost(path, responseFunction); 36 | case Method.Put: 37 | case Method.Delete: 38 | default: 39 | throw new ArgumentOutOfRangeException($"The method {nameof(method)} is not supported!"); 40 | } 41 | } 42 | 43 | private IRoutingTable MapGet( 44 | string path, 45 | Func responseFunction) 46 | { 47 | Guard.AgainstDuplicatedKey(routes[Method.Get], path, "RoutingTable.Get"); 48 | routes[Method.Get][path] = responseFunction; 49 | 50 | return this; 51 | } 52 | 53 | private IRoutingTable MapPost( 54 | string path, 55 | Func responseFunction) 56 | { 57 | Guard.AgainstDuplicatedKey(routes[Method.Post], path, "RoutingTable.Post"); 58 | routes[Method.Post][path] = responseFunction; 59 | 60 | return this; 61 | } 62 | 63 | public Response MatchRequest(Request request) 64 | { 65 | var requestMethod = request.Method; 66 | var requestUrl = request.Url; 67 | 68 | if (!this.routes.ContainsKey(requestMethod) 69 | || !this.routes[requestMethod].ContainsKey(requestUrl)) 70 | { 71 | return new NotFoundResponse(); 72 | } 73 | 74 | var responseFunction = this.routes[requestMethod][requestUrl]; 75 | 76 | return responseFunction(request); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /BasicWebServer.Server/Routing/RoutingTableExtension.cs: -------------------------------------------------------------------------------- 1 | using BasicWebServer.Server.Attributes; 2 | using BasicWebServer.Server.Controllers; 3 | using BasicWebServer.Server.HTTP; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Reflection; 9 | 10 | namespace BasicWebServer.Server.Routing 11 | { 12 | public static class RoutingTableExtension 13 | { 14 | public static IRoutingTable MapGet( 15 | this IRoutingTable routingTable, 16 | string path, 17 | Func controllerFunction) where TController : Controller 18 | => routingTable.Map( 19 | Method.Get, 20 | path, 21 | request => controllerFunction(CreateController(request))); 22 | 23 | public static IRoutingTable MapPost( 24 | this IRoutingTable routingTable, 25 | string path, 26 | Func controllerFunction) where TController : Controller 27 | => routingTable.Map( 28 | Method.Post, 29 | path, 30 | request => controllerFunction(CreateController(request))); 31 | 32 | public static IRoutingTable MapControllers(this IRoutingTable routingTable) 33 | { 34 | IEnumerable controllerActions = GetControllerActions(); 35 | 36 | foreach (var controllerAction in controllerActions) 37 | { 38 | string controllerName = controllerAction 39 | .DeclaringType 40 | .Name 41 | .Replace(nameof(Controller), string.Empty); 42 | 43 | string actionName = controllerAction.Name; 44 | string path = $"/{controllerName}/{actionName}"; 45 | 46 | var responseFunction = GetResponseFunction(controllerAction); 47 | 48 | Method httpMethod = Method.Get; 49 | var actionMethodAttribute = controllerAction 50 | .GetCustomAttribute(); 51 | 52 | if (actionMethodAttribute != null) 53 | { 54 | httpMethod = actionMethodAttribute.HttpMethod; 55 | } 56 | 57 | routingTable.Map(httpMethod, path, responseFunction); 58 | 59 | MapDefaultRoutes( 60 | routingTable, 61 | httpMethod, 62 | controllerName, 63 | actionName, 64 | responseFunction); 65 | } 66 | 67 | return routingTable; 68 | } 69 | 70 | public static IRoutingTable MapStaticFiles(this IRoutingTable routingTable, string folder = "wwwroot") 71 | { 72 | var currentDirectory = Directory.GetCurrentDirectory(); 73 | var staticFilesFolder = Path.Combine(currentDirectory, folder); 74 | 75 | if (!Directory.Exists(staticFilesFolder)) 76 | { 77 | return routingTable; 78 | } 79 | 80 | var staticFiles = Directory.GetFiles( 81 | staticFilesFolder, 82 | "*.*", 83 | SearchOption.AllDirectories); 84 | 85 | foreach (var file in staticFiles) 86 | { 87 | var relativePath = Path.GetRelativePath(staticFilesFolder, file); 88 | 89 | var urlPath = "/" + relativePath.Replace("\\", "/"); 90 | 91 | routingTable.Map(Method.Get, urlPath, request => 92 | { 93 | var content = File.ReadAllBytes(file); 94 | var fileExtension = Path.GetExtension(file).Trim('.'); 95 | var fileName = Path.GetFileName(file); 96 | var contentType = ContentType.GetByFileExtension(fileExtension); 97 | 98 | return new Response(StatusCode.OK) 99 | { 100 | FileContent = content 101 | }; 102 | }); 103 | } 104 | 105 | return routingTable; 106 | } 107 | 108 | private static Func GetResponseFunction(MethodInfo controllerAction) 109 | { 110 | return request => 111 | { 112 | if (!UserIsAuthorized(controllerAction, request.Session)) 113 | { 114 | return new Response(StatusCode.Unauthorized); 115 | } 116 | 117 | var controllerInstance = CreateController(controllerAction.DeclaringType, request); 118 | var parameterValues = GetParameterValues(controllerAction, request); 119 | 120 | return (Response)controllerAction.Invoke(controllerInstance, parameterValues); 121 | }; 122 | } 123 | 124 | private static object[] GetParameterValues(MethodInfo controllerAction, Request request) 125 | { 126 | var actionParameters = controllerAction 127 | .GetParameters() 128 | .Select(p => new 129 | { 130 | p.Name, 131 | p.ParameterType 132 | }) 133 | .ToArray(); 134 | 135 | var parameterValues = new object[actionParameters.Length]; 136 | 137 | for (int i = 0; i < actionParameters.Length; i++) 138 | { 139 | var parameter = actionParameters[i]; 140 | 141 | if (parameter.ParameterType.IsPrimitive || 142 | parameter.ParameterType == typeof(string)) 143 | { 144 | try 145 | { 146 | string parameterValue = request.GetValue(parameter.Name); 147 | parameterValues[i] = Convert.ChangeType(parameterValue, parameter.ParameterType); 148 | } 149 | catch (Exception) 150 | {} 151 | } 152 | else 153 | { 154 | var parameterValue = Activator.CreateInstance(parameter.ParameterType); 155 | var parameterProperties = parameter.ParameterType.GetProperties(); 156 | 157 | foreach (var property in parameterProperties) 158 | { 159 | try 160 | { 161 | var propertyValue = request.GetValue(property.Name); 162 | property.SetValue( 163 | parameterValue, 164 | Convert.ChangeType(propertyValue, property.PropertyType)); 165 | } 166 | catch (Exception) 167 | {} 168 | } 169 | 170 | parameterValues[i] = parameterValue; 171 | } 172 | } 173 | 174 | return parameterValues; 175 | } 176 | 177 | private static IEnumerable GetControllerActions() 178 | => Assembly 179 | .GetEntryAssembly() 180 | .GetExportedTypes() 181 | .Where(t => t.IsAbstract == false) 182 | .Where(t => t.IsAssignableTo(typeof(Controller))) 183 | .Where(t => t.Name.EndsWith(nameof(Controller))) 184 | .SelectMany(t => t 185 | .GetMethods(BindingFlags.Instance | BindingFlags.Public) 186 | .Where(m => m.ReturnType.IsAssignableTo(typeof(Response))) 187 | ).ToList(); 188 | 189 | private static TController CreateController(Request request) 190 | => (TController)Activator.CreateInstance(typeof(TController), new[] { request }); 191 | 192 | private static Controller CreateController(Type controllerType, Request request) 193 | { 194 | var controller = (Controller)Request.ServiceCollection.CreateInstance(controllerType); 195 | 196 | controllerType 197 | .GetProperty("Request", BindingFlags.Instance | BindingFlags.NonPublic) 198 | .SetValue(controller, request); 199 | 200 | return controller; 201 | } 202 | 203 | private static string GetValue(this Request request, string name) 204 | => request.Query.GetValueOrDefault(name) ?? 205 | request.Form.GetValueOrDefault(name); 206 | 207 | private static void MapDefaultRoutes( 208 | IRoutingTable routingTable, 209 | Method httpMethod, 210 | string controllerName, 211 | string actionName, 212 | Func responseFunction) 213 | { 214 | const string defaultActionName = "Index"; 215 | const string defaultControllerName = "Home"; 216 | 217 | if (actionName == defaultActionName) 218 | { 219 | routingTable.Map(httpMethod, $"/{controllerName}", responseFunction); 220 | 221 | if (controllerName == defaultControllerName) 222 | { 223 | routingTable.Map(httpMethod, "/", responseFunction); 224 | } 225 | } 226 | } 227 | 228 | private static bool UserIsAuthorized( 229 | MethodInfo controllerAction, 230 | Session session) 231 | { 232 | var authorizationRequired = controllerAction 233 | .DeclaringType 234 | .GetCustomAttribute() 235 | ?? controllerAction 236 | .GetCustomAttribute(); 237 | 238 | if (authorizationRequired != null) 239 | { 240 | var userIsAuthorized = session.ContainsKey(Session.SessionUserKey) 241 | && session[Session.SessionUserKey] != null; 242 | 243 | if (!userIsAuthorized) 244 | { 245 | return false; 246 | } 247 | } 248 | 249 | return true; 250 | } 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /BasicWebServer.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31729.503 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BasicWebServer.Server", "BasicWebServer.Server\BasicWebServer.Server.csproj", "{F6260181-0C0A-4509-8933-E2474E97AE02}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicWebServer.Demo", "BasicWebServer.Demo\BasicWebServer.Demo.csproj", "{ACC6BA72-F2DC-47B4-83C1-769BEDC2F692}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {F6260181-0C0A-4509-8933-E2474E97AE02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {F6260181-0C0A-4509-8933-E2474E97AE02}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {F6260181-0C0A-4509-8933-E2474E97AE02}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {F6260181-0C0A-4509-8933-E2474E97AE02}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {ACC6BA72-F2DC-47B4-83C1-769BEDC2F692}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {ACC6BA72-F2DC-47B4-83C1-769BEDC2F692}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {ACC6BA72-F2DC-47B4-83C1-769BEDC2F692}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {ACC6BA72-F2DC-47B4-83C1-769BEDC2F692}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {33EF20BB-3E0F-42D1-8A9F-1B1E80B601C3} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebBasic2022 2 | 3 | The purpose of this application is to show some basic concepts and patterns. It is developed for educational purposes and is used as demo in January 2022 C# Web Basics course in SoftUni. It has very basic functionality, but is used as showcase for the following patterns and concepts: 4 | 5 | 1. **Web basics** 6 | 7 | - Parsing HTTP requets 8 | - HTTP Methods 9 | - HTTP Headers 10 | - Cookies 11 | - Session 12 | - HTTP response 13 | - HTTP Status codes 14 | - Downloading files 15 | 16 | 2. **Routing** 17 | 18 | - Static routing table 19 | - Building dynamic routing table based on conventions and reflection 20 | 21 | 3. **MVC** 22 | 23 | - Controllers 24 | - Models 25 | - Views / Basic template engine 26 | 27 | 4. **Inversion of control** 28 | 29 | - IoC container 30 | - Constructor injection 31 | 32 | 5. **Data binding** 33 | 34 | - Binding of primitive values 35 | - Binding of complex models 36 | - Binding from Form data and Query string 37 | 38 | 6. **User authorization** 39 | 40 | - Basic authorization mechanism 41 | 42 | *Improvements to components and patterns are warmly welcomed!* 43 | --------------------------------------------------------------------------------