kema

RequestHandler

Oct 18th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 KB | None | 0 0
  1. namespace MyCoolWebServer.Server.Handlers
  2. {
  3.     using Common;
  4.     using Contracts;
  5.     using Http;
  6.     using Http.Contracts;
  7.     using System;
  8.  
  9.     public class RequestHandler : IRequestHandler
  10.     {
  11.         private readonly Func<IHttpRequest, IHttpResponse> handlingFunc;
  12.        
  13.         public RequestHandler(Func<IHttpRequest, IHttpResponse> handlingFunc)
  14.         {
  15.             CoreValidator.ThrowIfNull(handlingFunc, nameof(handlingFunc));
  16.  
  17.             this.handlingFunc = handlingFunc;
  18.         }
  19.  
  20.         public IHttpResponse Handle(IHttpContext context)
  21.         {
  22.             string sessionIdToSend = null;
  23.  
  24.             if (!context.Request.Cookies.ContainsKey(SessionStore.SessionCookieKey))
  25.             {
  26.                 var sessionId = Guid.NewGuid().ToString();
  27.  
  28.                 context.Request.Session = SessionStore.Get(sessionId);
  29.  
  30.                 sessionIdToSend = sessionId;
  31.             }
  32.  
  33.             var response = this.handlingFunc(context.Request);
  34.  
  35.             if (sessionIdToSend != null)
  36.             {
  37.                 response.Headers.Add(
  38.                     HttpHeader.SetCookie,
  39.                     $"{SessionStore.SessionCookieKey}={sessionIdToSend}; HttpOnly; path=/");
  40.             }
  41.            
  42.             if (!response.Headers.ContainsKey(HttpHeader.ContentType))
  43.             {
  44.                 response.Headers.Add(HttpHeader.ContentType, "text/plain");
  45.             }
  46.  
  47.             foreach (var cookie in response.Cookies)
  48.             {
  49.                 response.Headers.Add(HttpHeader.SetCookie, cookie.ToString());
  50.             }
  51.  
  52.             return response;
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment