Advertisement
Danny_Berova

ResourceRouter

Jun 22nd, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. namespace SimpleMvc.Framework.Routers
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.IO;
  6.     using System.Linq;
  7.     using WebServer.Contracts;
  8.     using WebServer.Enums;
  9.     using WebServer.Http.Contracts;
  10.     using WebServer.Http.Response;
  11.  
  12.     public class ResourceRouter : IHandleable
  13.     {
  14.         private const string ContentDirectory = "../../../Content/";
  15.  
  16.         private static readonly Dictionary<string, string> ExtensionsToMIMETypes = new Dictionary<string, string>()
  17.         {
  18.             ["js"] = "application/javascript",
  19.             ["css"] = "text/css",
  20.             ["html"] = "text/html"
  21.         };
  22.  
  23.         public IHttpResponse Handle(IHttpRequest request)
  24.         {
  25.             try
  26.             {
  27.                 //string[] resourcePath = request.Path.Split('/', 3);
  28.  
  29.                 //// The first part will always be empty, as it begins with '/'
  30.                 //// The second part may be either a controller path or a direct resource
  31.                 //if (resourcePath.Length > 2)
  32.                 //{
  33.                 //    folderPath = resourcePath[2];
  34.                 //}
  35.  
  36.                 string folderPath = request.Path;
  37.                 string extension = folderPath.Split(".").Last();
  38.  
  39.                 if (!ExtensionsToMIMETypes.ContainsKey(extension))
  40.                 {
  41.                     throw new InvalidOperationException("The file type is not supported.");
  42.                 }
  43.  
  44.                 byte[] fileContent = this.ReadFileContent(folderPath);
  45.                 return new FileResponse(HttpStatusCode.Ok, fileContent, ExtensionsToMIMETypes[extension]);
  46.             }
  47.             catch(Exception)
  48.             {
  49.                 return new NotFoundResponse();
  50.             }
  51.         }
  52.  
  53.         private byte[] ReadFileContent(string fileFullName)
  54.         {
  55.             return File.ReadAllBytes(ContentDirectory + fileFullName);
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement