Exemple #1
0
 /// <summary>
 ///     Sends headers to disable caching on the client side.
 /// </summary>
 /// <param name="context">The context.</param>
 public static void NoCache(this HttpListenerContext context)
 {
     context.Response.AddHeader(Headers.Expires, "Mon, 26 Jul 1997 05:00:00 GMT");
     context.Response.AddHeader(Headers.LastModified, DateTime.UtcNow.ToString(Strings.BrowserTimeFormat, Strings.StandardCultureInfo));
     context.Response.AddHeader(Headers.CacheControl, "no-store, no-cache, must-revalidate");
     context.Response.AddHeader(Headers.Pragma, "no-cache");
 }
        /// <summary>
        ///     Fixes the session cookie to match the correct value.
        ///     System.Net.Cookie.Value only supports a single value and we need to pick the one that potentially exists.
        /// </summary>
        /// <param name="context">The context.</param>
        private void FixupSessionCookie(HttpListenerContext context)
        {
            // get the real "__session" cookie value because sometimes there's more than 1 value and System.Net.Cookie only supports 1 value per cookie
            if (context.Request.Headers[Headers.Cookie] == null)
            {
                return;
            }

            var cookieItems = context.Request.Headers[Headers.Cookie].Split(Strings.CookieSplitChars, StringSplitOptions.RemoveEmptyEntries);

            foreach (var cookieItem in cookieItems)
            {
                var nameValue = cookieItem.Trim().Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (nameValue.Length == 2 && nameValue[0].Equals(SessionCookieName))
                {
                    var sessionIdValue = nameValue[1].Trim();

                    if (!_sessions.ContainsKey(sessionIdValue))
                    {
                        continue;
                    }

                    context.Request.Cookies[SessionCookieName].Value = sessionIdValue;
                    break;
                }
            }
        }
Exemple #3
0
        /// <summary>
        ///     Outputs async a string response given a string.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="content">The content.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>A task for writing the output stream.</returns>
        public static async Task <bool> StringResponseAsync(this HttpListenerContext context, string content, string contentType = "application/json", CancellationToken cancellationToken = default, Encoding encoding = null)
        {
            var buffer = (encoding ?? Encoding.UTF8).GetBytes(content);

            context.Response.ContentType = contentType;
            await context.Response.OutputStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);

            return(true);
        }
        /// <inheritdoc />
        public SessionInfo GetSession(HttpListenerContext context)
        {
            lock (_sessionsSyncLock)
            {
                if (context.Request.Cookies[SessionCookieName] == null)
                {
                    return(null);
                }

                var cookieValue = context.Request.Cookies[SessionCookieName].Value;
                return(this[cookieValue]);
            }
        }
Exemple #5
0
        /// <summary>
        ///     Sets a response static code of 302 and adds a Location header to the response
        ///     in order to direct the client to a different URL.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="location">The location.</param>
        /// <param name="useAbsoluteUrl">if set to <c>true</c> [use absolute URL].</param>
        /// <returns><b>true</b> if the headers were set, otherwise <b>false</b>.</returns>
        public static bool Redirect(this HttpListenerContext context, string location, bool useAbsoluteUrl = true)
        {
            if (useAbsoluteUrl)
            {
                var hostPath = context.Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped);
                location = hostPath + location;
            }

            context.Response.StatusCode = 302;
            context.Response.AddHeader("Location", location);

            return(true);
        }
Exemple #6
0
        /// <summary>
        ///     Retrieves the request body as a string.
        ///     Note that once this method returns, the underlying input stream cannot be read again as
        ///     it is not rewindable for obvious reasons. This functionality is by design.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        ///     The rest of the stream as a string, from the current position to the end.
        ///     If the current position is at the end of the stream, returns an empty string.
        /// </returns>
        public static string RequestBody(this HttpListenerContext context)
        {
            if (context.Request.HasEntityBody == false)
            {
                return(null);
            }

            using (var body = context.Request.InputStream) // here we have data
            {
                using (var reader = new StreamReader(body, context.Request.ContentEncoding))
                {
                    return(reader.ReadToEnd());
                }
            }
        }
Exemple #7
0
        /// <summary>
        ///     Gets the request path for the specified context using a wildcard paths to
        ///     match.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="wildcardPaths">The wildcard paths.</param>
        /// <returns>Path for the specified context.</returns>
        public static string RequestWilcardPath(this HttpListenerContext context, IEnumerable <string> wildcardPaths)
        {
            var path = context.Request.Url.LocalPath.ToLowerInvariant();

            var wildcardMatch = wildcardPaths.FirstOrDefault(p => // wildcard at the end
                                                             path.StartsWith(p.Substring(0, p.Length - ModuleMap.AnyPath.Length))

                                                             // wildcard in the middle so check both start/end
                                                             || path.StartsWith(p.Substring(0, p.IndexOf(ModuleMap.AnyPath, StringComparison.Ordinal))) &&
                                                             path.EndsWith(p.Substring(p.IndexOf(ModuleMap.AnyPath, StringComparison.Ordinal) + 1)));

            if (string.IsNullOrWhiteSpace(wildcardMatch) == false)
            {
                path = wildcardMatch;
            }

            return(path);
        }
Exemple #8
0
 /// <summary>
 ///     Outputs async a Json Response given a data object.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="data">The data.</param>
 /// <returns>A <c>true</c> value of type ref=JsonResponseAsync".</returns>
 public static Task <bool> JsonResponseAsync(this HttpListenerContext context, object data)
 {
     return(context.JsonResponseAsync(Json.Serialize(data)));
 }
Exemple #9
0
 /// <summary>
 ///     Outputs a Json Response given a data object.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="data">The data.</param>
 /// <returns>A <c>true</c> value of type ref=JsonResponseAsync".</returns>
 public static bool JsonResponse(this HttpListenerContext context, object data)
 {
     return(context.JsonResponseAsync(data).GetAwaiter().GetResult());
 }
Exemple #10
0
 /// <summary>
 ///     Returns dictionary from Request POST data
 ///     Please note the underlying input stream is not rewindable.
 /// </summary>
 /// <param name="context">The context to request body as string.</param>
 /// <returns>A collection that represents KVPs from request data.</returns>
 public static Dictionary <string, object> RequestFormDataDictionary(this HttpListenerContext context)
 {
     return(RequestFormDataDictionary(context.RequestBody()));
 }
Exemple #11
0
 /// <summary>
 ///     Deletes the session object associated to the current context.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="context">The context.</param>
 public static void DeleteSession(this WebServer server, HttpListenerContext context)
 {
     server.SessionModule?.DeleteSession(context);
 }
Exemple #12
0
 /// <summary>
 ///     Outputs a HTML Response given a HTML content.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="htmlContent">Content of the HTML.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>A task for writing the output stream.</returns>
 public static Task <bool> HtmlResponseAsync(this HttpListenerContext context, string htmlContent, HttpStatusCode statusCode = HttpStatusCode.OK, CancellationToken cancellationToken = default)
 {
     context.Response.StatusCode = (int)statusCode;
     return(context.StringResponseAsync(htmlContent, Responses.HtmlContentType, cancellationToken));
 }
Exemple #13
0
 /// <summary>
 ///     Determines whether [has request header] [the specified context].
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="headerName">Name of the header.</param>
 /// <returns>True if request headers is not a null; otherwise, false.</returns>
 public static bool HasRequestHeader(this HttpListenerContext context, string headerName)
 {
     return(context.Request.Headers[headerName] != null);
 }
Exemple #14
0
 /// <summary>
 ///     Retrieves the specified request the header.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="headerName">Name of the header.</param>
 /// <returns>Specified request the header when is true; otherwise, empty string. </returns>
 public static string RequestHeader(this HttpListenerContext context, string headerName)
 {
     return(context.Request.Headers[headerName] ?? string.Empty);
 }
Exemple #15
0
 /// <summary>
 ///     Determines if a key exists within the Request's query string.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="key">The key.</param>
 /// <returns>True if a key exists within the Request's query string; otherwise, false.</returns>
 public static bool InQueryString(this HttpListenerContext context, string key)
 {
     return(context.Request.QueryString.AllKeys.Contains(key));
 }
Exemple #16
0
 /// <summary>
 ///     Gets the value for the specified query string key.
 ///     If the value does not exist it returns null.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="key">The key.</param>
 /// <returns>A string that represents the value for the specified query string key.</returns>
 public static string QueryString(this HttpListenerContext context, string key)
 {
     return(context.InQueryString(key) ? context.Request.QueryString[key] : null);
 }
Exemple #17
0
 /// <summary>
 ///     Retrieves the Request HTTP Verb (also called Method) of this context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>HTTP verb result of the conversion of this context.</returns>
 public static HttpVerbs RequestVerb(this HttpListenerContext context)
 {
     Enum.TryParse(context.Request.HttpMethod.ToLowerInvariant().Trim(), true, out HttpVerbs verb);
     return(verb);
 }
Exemple #18
0
 /// <summary>
 ///     Gets the request path for the specified context case sensitive.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>Path for the specified context.</returns>
 public static string RequestPathCaseSensitive(this HttpListenerContext context)
 {
     return(context.Request.Url.LocalPath);
 }
Exemple #19
0
 /// <summary>
 ///     Outputs a Json Response given a Json string.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="json">The JSON.</param>
 /// <returns> A <c>true</c> value of type ref=JsonResponseAsync".</returns>
 public static bool JsonResponse(this HttpListenerContext context, string json)
 {
     return(context.JsonResponseAsync(json).GetAwaiter().GetResult());
 }
Exemple #20
0
 /// <summary>
 ///     Outputs async a JSON Response given a JSON string.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="json">The JSON.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>A task for writing the output stream.</returns>
 public static Task <bool> JsonResponseAsync(this HttpListenerContext context, string json, CancellationToken cancellationToken = default)
 {
     return(context.StringResponseAsync(json, cancellationToken: cancellationToken));
 }
 /// <inheritdoc />
 public void DeleteSession(HttpListenerContext context)
 {
     DeleteSession(GetSession(context));
 }
Exemple #22
0
 /// <summary>
 ///     Outputs a JSON Response given an exception.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="ex">The ex.</param>
 /// <param name="statusCode">The status code.</param>
 /// <returns>A task for writing the output stream.</returns>
 public static Task <bool> JsonExceptionResponseAsync(this HttpListenerContext context, Exception ex, HttpStatusCode statusCode = HttpStatusCode.InternalServerError)
 {
     context.Response.StatusCode = (int)statusCode;
     return(context.JsonResponseAsync(ex));
 }
Exemple #23
0
 /// <summary>
 ///     Deletes the session object associated to the current context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="server">The server.</param>
 public static void DeleteSession(this HttpListenerContext context, WebServer server)
 {
     server.DeleteSession(context);
 }
Exemple #24
0
 /// <summary>
 ///     Parses the JSON as a given type from the request body.
 ///     Please note the underlying input stream is not rewindable.
 /// </summary>
 /// <typeparam name="T">The type of specified object type.</typeparam>
 /// <param name="context">The context.</param>
 /// <returns>
 ///     Parses the json as a given type from the request body.
 /// </returns>
 public static T ParseJson <T>(this HttpListenerContext context) where T : class
 {
     return(ParseJson <T>(context.RequestBody()));
 }
Exemple #25
0
 /// <summary>
 ///     Gets the session object associated to the current context.
 ///     Returns null if the LocalSessionWebModule has not been loaded.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="context">The context.</param>
 /// <returns>A session info for the given server context.</returns>
 public static SessionInfo GetSession(this WebServer server, HttpListenerContext context)
 {
     return(server.SessionModule?.GetSession(context));
 }
Exemple #26
0
 /// <summary>
 ///     Requests the wildcard URL parameters.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="basePath">The base path.</param>
 /// <returns>The params from the request.</returns>
 public static string[] RequestWildcardUrlParams(this HttpListenerContext context, string basePath)
 {
     return(RequestWildcardUrlParams(context.RequestPath(), basePath));
 }
Exemple #27
0
 /// <summary>
 ///     Gets the request path for the specified context.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns>Path for the specified context.</returns>
 public static string RequestPath(this HttpListenerContext context)
 {
     return(context.Request.Url.LocalPath.ToLowerInvariant());
 }
Exemple #28
0
 /// <summary>
 ///     Requests the regex URL parameters.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="basePath">The base path.</param>
 /// <returns>The params from the request.</returns>
 public static Dictionary <string, object> RequestRegexUrlParams(this HttpListenerContext context, string basePath)
 {
     return(RequestRegexUrlParams(context.RequestPath(), basePath));
 }
Exemple #29
0
 /// <summary>
 ///     Gets the session object associated to the current context.
 ///     Returns null if the LocalSessionWebModule has not been loaded.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="server">The server.</param>
 /// <returns>A session object for the given server context.</returns>
 public static SessionInfo GetSession(this HttpListenerContext context, WebServer server)
 {
     return(server.GetSession(context));
 }