public static async Task CopyFromAsync(this HttpListenerResponse response, HttpResponseMessage message,
            IContentProcessor contentProcessor)
        {
            response.StatusCode = (int) message.StatusCode;
            foreach (var httpResponseHeader in message.Headers.Where(header => !Filter.Contains(header.Key)))
            {
                foreach (var value in httpResponseHeader.Value)
                {
                    response.AddHeader(httpResponseHeader.Key, value);
                }
            }
            foreach (var httpResponseHeader in message.Content.Headers.Where(header => !Filter.Contains(header.Key)))
            {
                foreach (var value in httpResponseHeader.Value)
                {
                    response.AddHeader(httpResponseHeader.Key, value);
                }
            }
            response.SendChunked = false;
            response.KeepAlive = false;

            var bytes = await message.Content.ReadAsByteArrayAsync();

            if (bytes.Length <= 0) return;

            if (contentProcessor != null)
            {
                bytes = contentProcessor.Process(bytes, message.Content.Headers.ContentType,
                    message.RequestMessage.RequestUri);
            }

            response.ContentLength64 = bytes.Length;
            await response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
        }
 /// <summary>
 /// Builds a response that will return a binary file to the client.
 /// </summary>
 /// <param name="response">The <see cref="HttpResponse"/> that acts as the this instance.</param>
 /// <param name="fileName">The name of the file.</param>
 /// <param name="fileContents">The file contents.</param>
 /// <param name="encoding">The character encoding of the file. Defaults to <see cref="UTF8Encoding"/>.</param>
 /// <param name="contentType">The Internet Media Type. See <see cref="InternetMediaType"/> for a valid list of values.</param>
 public static void BuildBinaryFileResponse(this HttpResponse response, string fileName, byte[] fileContents, Encoding encoding, string contentType = InternetMediaType.Null)
 {
     response.AddHeader(HttpResponseHeader.ContentDispositionKey, string.Format(HttpResponseHeader.ContentDispositionValueFormat, HttpUtility.UrlPathEncode(fileName)));
     response.AddHeader(HttpResponseHeader.ContentLengthKey, fileContents.Length.ToString());
     response.AddHeader(HttpResponseHeader.PragmaKey, HttpResponseHeader.PragmaValuePublic);
     response.ContentType = contentType;
     response.Charset = encoding.HeaderName;
     response.ContentEncoding = encoding;
     response.BinaryWrite(fileContents);
 }
Example #3
0
        public static void ReturnCsv(this HttpResponse response, string csvText)
        {
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = "text/csv";
            response.AddHeader("content-disposition", "attachment; filename=eway.csv");
            response.AddHeader("Pragma", "public");

            response.Write(csvText);

            response.End();
        }
        public static void DownloadFile(this HttpResponse source, DownloadableFile file)
        {
            var contentData = file.ContentData.IsEmpty()
                                  ? file.ContentText.GetBytes(source.ContentEncoding)
                                  : file.ContentData;

            source.Clear();
            source.Buffer = false;
            source.AddHeader("Accept-Ranges", "bytes");
            source.AddHeader("Content-Disposition", "attachment;filename=\"" + file.FileName + "\"");
            source.AddHeader("Connection", "Keep-Alive");
            source.ContentType = file.ContentType;
            source.BinaryWrite(contentData);
            source.End();
        }
Example #5
0
 public static void JsonResult(this HttpResponse response, object data)
 {
     response.Clear();
     response.AddHeader("Content-Type", "application/json");
     response.Write(LogManager.JsonSerializer.SerializeObject(data));
     response.End();
 }
        public static void SetSourcePersistenceId(this MessagePayload payload, MessagePersistenceId id)
        {
            Contract.Requires(id != null);

            payload.RemoveHeader(typeof(SourcePersistenceHeader));
            payload.AddHeader(new SourcePersistenceHeader(id));
        }
 /// <summary>
 /// Sets a persistent cookie with an expiresAt date
 /// </summary>
 public static void SetCookie(this IHttpResponse httpRes, string cookieName, 
     string cookieValue, DateTime expiresAt, string path)
 {
     path = path ?? "/";
     var cookie = string.Format("{0}={1};expires={2};path={3}", cookieName, cookieValue, expiresAt.ToString("R"), path);
     httpRes.AddHeader(HttpHeaders.SetCookie, cookie);
 }
Example #8
0
 public static void MergeBang(this HttpResponseBase res, Dictionary<string, string> hdrs)
 {
     foreach (var hdr in hdrs)
     {
         res.AddHeader(hdr.Key, hdr.Value);
     }
 }
Example #9
0
 static private void AddHeaders(this HttpWebRequest req, Dictionary<string, string> headers)
 {
     foreach (var h in headers)
     {
         req.AddHeader(h.Key, h.Value);
     }
 }
 public static void ApplyGlobalResponseHeaders(this IHttpResponse httpRes)
 {
     foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
Example #11
0
 public static void HtmlResult(this HttpResponse response, string html)
 {
     response.Clear();
     response.AddHeader("Content-Type", "text/html");
     response.Write(html);
     response.End();
 }
 //Forces Download/Save rather than opening in Browser//
 public static void ForceDownload(this HttpResponse Response, string virtualPath, string fileName)
 {
     Response.Clear();
     Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
     Response.WriteFile(virtualPath);
     Response.ContentType = "";
     Response.End();
 }
 /// <summary>
 ///     A HttpResponse extension method that sends an attachment.
 /// </summary>
 /// <param name="this">The @this to act on.</param>
 /// <param name="fullPathToFile">The full path to file.</param>
 /// <param name="outputFileName">Filename of the output file.</param>
 public static void SendAttachment(this HttpResponse @this, string fullPathToFile, string outputFileName)
 {
     @this.Clear();
     @this.AddHeader("content-disposition", "attachment; filename=" + outputFileName);
     @this.WriteFile(fullPathToFile);
     @this.ContentType = "";
     @this.End();
 }
 public static IMessageBuilder AddHeaders(this IMessageBuilder messageBuilder, IEnumerable<IMessageHeaderWithMustUnderstandSpecification> headers)
 {
     foreach (var header in headers)
     {
         messageBuilder.AddHeader(header.Header, header.MustUnderstand);
     }
     return messageBuilder;
 }
Example #15
0
        public static void AddTogglAuth(this IRestRequest req, TogglAuthRequest auth)
        {
            string encodedAuthString = String.IsNullOrWhiteSpace(auth.ApiToken) ?
                Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.UserName + ":" + auth.Password)) :
                Convert.ToBase64String(Encoding.UTF8.GetBytes(auth.ApiToken + ":api_token"));

            req.AddHeader("Authorization", "Basic " + encodedAuthString);
        }
 public static void ApplyGlobalResponseHeaders(this HttpResponseBase httpRes)
 {
     if (HostContext.Config == null) return;
     foreach (var globalResponseHeader in HostContext.Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
 public static void ApplyGlobalResponseHeaders(this IResponse httpRes)
 {
     if (!ShouldWriteGlobalHeaders(httpRes)) return;
     foreach (var globalResponseHeader in HostContext.Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
 public static void ApplyGlobalResponseHeaders(this HttpListenerResponse httpRes)
 {
     if (EndpointHost.Config == null) return;
     foreach (var globalResponseHeader in EndpointHost.Config.GlobalResponseHeaders)
     {
         httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value);
     }
 }
Example #19
0
        /// <summary>
        /// Sets the cache control.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="cacheControl">The cache control.</param>
        /// <returns>The Http Response</returns>
        public static HttpResponse SetHeaderCacheControl(this HttpResponse response, string cacheControl = "public, max-age=84600")
        {
            if (response != null)
            {
                response.AddHeader("Cache-Control", cacheControl);
            }

            return response;
        }
        /// <summary>   
        /// A HttpResponse extension method that disables the caching by setting Cacheability to HttpCacheability.NoCache, setting Expiration to
        /// DateTime.Now and add the pragma:no-cache header. 
        /// </summary>
        /// <remarks>   ebrown, 11/10/2010. </remarks>
        /// <exception cref="ArgumentNullException">    Thrown when one or more required arguments are null. </exception>
        /// <param name="response"> The response to act on. </param>
        public static void DisableCaching(this HttpResponseBase response)
        {
            if (null == response) { throw new ArgumentNullException("response"); }

            var cache = response.Cache;
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetExpires(DateTime.Now);
            response.AddHeader("pragma", "no-cache");
        }
Example #21
0
        public static void ResourceNotFound(this HttpResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            response.ClearContent();
            response.AddHeader("Content-Length", 0.ToString());
            response.StatusCode = (int) HttpStatusCode.NotFound;
        }
        public static void SetPersistenceId(
            this MessagePayload payload, 
            EndpointAddress address, 
            PersistenceUseType useType)
        {
            Contract.Requires(address != null);
            Contract.Requires(address != EndpointAddress.Empty);

            payload.RemoveHeader(typeof(PersistenceHeader));
            payload.AddHeader(new PersistenceHeader(new MessagePersistenceId(payload.Id, address, useType)));
        }
Example #23
0
        /// <summary>
        /// Sets the content type header.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="contenttype">The content type.</param>
        /// <returns>
        /// The Http Response
        /// </returns>
        public static HttpResponse SetHeaderContentType(this HttpResponse response, string contenttype)
        {
            if (response != null)
            {
                if (!string.IsNullOrWhiteSpace(contenttype))
                {
                    response.AddHeader("Content-Type", contenttype);
                }
            }

            return response;
        }
        public static async Task WriteTextAsync(this HttpListenerResponse response, string text)
        {
            response.AddHeader("Charset", Encoding.UTF8.WebName);

            response.ContentEncoding = Encoding.UTF8;

            var bytes = Encoding.UTF8.GetBytes(text);

            response.ContentLength64 = bytes.LongLength;

            await response.OutputStream.WriteAsync(bytes, 0, bytes.Length);
        }
Example #25
0
        /// <summary>
        /// Sets the header Etag.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="etag">The Etag.</param>
        /// <returns>The Http Response</returns>
        public static HttpResponse SetHeaderEtag(this HttpResponse response, object etag)
        {
            if (response != null)
            {
                var value = string.Concat(etag);
                if (!string.IsNullOrWhiteSpace(value))
                {
                    response.AddHeader("Etag", value);
                }
            }

            return response;
        }
        public static void PermanentRedirect(this HttpResponse response, string location)
        {
            if (null == response)
            {
                return;
            }

            response.Status = "301 Moved permanently";
            response.StatusCode = 301;
            response.AddHeader(
                "Location",
                location);
        }
        public static void WriteResult(this HttpListenerResponse response, HttpStatusCode statusCode, string text)
        {
            response.StatusCode = (int)statusCode;

            response.AddHeader("Charset", Encoding.UTF8.WebName);

            response.ContentEncoding = Encoding.UTF8;

            var bytes = Encoding.UTF8.GetBytes(text);

            response.ContentLength64 = bytes.LongLength;

            response.OutputStream.Write(bytes, 0, bytes.Length);
        }
        public static void Location(this HttpResponseBase value, HttpRequestBase requestBase, string path)
        {
            if (requestBase == null || requestBase.Url == null)
            {
                throw new ArgumentNullException("requestBase");
            }

            var urlBuilder = new UriBuilder(requestBase.Url.AbsoluteUri)
                             {
                                 Path = path
                             };

            value.AddHeader("Location", urlBuilder.Uri.AbsoluteUri);
        }
 public static void ReturnAuthRequired(this IHttpResponse httpRes, string authRealm)
 {
     httpRes.StatusCode = (int)HttpStatusCode.Unauthorized;
     httpRes.AddHeader(HttpHeaders.WwwAuthenticate, "Basic realm=\"" + authRealm + "\"");
     httpRes.Close();
 }
 public static void RedirectToUrl(this IHttpResponse httpRes, string url)
 {
     httpRes.AddHeader(HttpHeaders.Location, url);
     httpRes.Close();
 }