private static bool WriteFileDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(filePath);
                if (fileInfo.Length >= MAXSIZE)
                {
                    throw new Exception(SizeOver2GException);
                }

                return(ExecuteDownload(response, () =>
                {
                    response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    response.AddHeader("Content-Transfer-Encoding", "binary");

                    response.WriteFile(fileInfo.FullName);
                }, true, filePath, fileName, encoding));
            }
            catch
            {
                if (response != null)
                {
                    response.Close();
                }
                throw;
            }
        }
 protected override void WriteFile(HttpResponseBase response)
 {
     base.WriteFile(response);
     response.Flush();
     response.Close();
     File.Delete(FileName);
 }
Exemplo n.º 3
0
 /// <summary>
 /// End a ServiceStack Request
 /// </summary>
 public static void EndRequest(this HttpResponseBase httpRes, bool skipHeaders = false)
 {
     if (!skipHeaders)
     {
         httpRes.ApplyGlobalResponseHeaders();
     }
     httpRes.Close();
     HostContext.CompleteRequest(null);
 }
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            response.Clear();
            response.ContentType = "text/csv";
            response.AddHeader("content-disposition", "attachment; filename=QueryResults.csv");
            response.AddHeader("content-length", Encoding.UTF8.GetByteCount(RawCsv).ToString());
            response.AddHeader("Pragma", "public");
            response.Write(RawCsv);
            response.Flush();
            response.Close();
        }
        private static bool WriteFilePortionDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding)
        {
            FileStream fileStream = null;

            try
            {
                return(ExecuteDownload(response, () =>
                {
                    byte[] buffer = new byte[CHUNKSIZE];
                    using (fileStream = File.OpenRead(filePath))
                    {
                        response.AddHeader("Content-Length", fileStream.Length.ToString());

                        long fileSize = fileStream.Length;
                        while (fileSize > 0 && response.IsClientConnected)
                        {
                            int readSize = fileStream.Read(buffer, 0, Convert.ToInt32(CHUNKSIZE));
                            response.OutputStream.Write(buffer, 0, readSize);
                            response.Flush();
                            fileSize = fileSize - readSize;
                        }
                    }
                    response.Close();
                }, false, filePath, fileName, encoding));
            }
            catch
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }

                throw;
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Unauthorization handler
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            HttpResponseBase httpResponse = GetResponse(filterContext);

            httpResponse.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
            //httpResponse.Status = "Forbidden";
            httpResponse.StatusDescription = "Unauthorized Page";
            httpResponse.End();
            httpResponse.Close();

            //filterContext.Result = new HttpUnauthorizedResult();

            base.HandleUnauthorizedRequest(filterContext);
        }
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            string attachment = "attachment; filename=ExecutionPlan.sqlplan";

            response.Clear();
            response.ContentType = "text/xml";
            response.AddHeader("content-disposition", attachment);
            response.AddHeader("Pragma", "public");
            response.Write(plan);
            response.Flush();
            response.Close();
        }
Exemplo n.º 8
0
        public virtual void Export()
        {
            _response.Clear();
            _response.ClearHeaders();

            _response.AppendHeader("Content-Length", (this as IExport).Length.ToString());
            _response.ContentType = (this as IExport).ContentType;
            _response.AppendHeader("Content-Disposition", $"attachment;filename=\"{GetName}.{(this as IExport).Extension}\"");

            _response.ContentType = (this as IExport).ContentType;
            _response.Write(_result);

            _response.End();
            _response.Close();
        }
 private static bool TransmitFileDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding)
 {
     try
     {
         return(ExecuteDownload(response, () =>
         {
             response.TransmitFile(filePath);
         }, true, filePath, fileName, encoding));
     }
     catch
     {
         if (response != null)
         {
             response.Close();
         }
         throw;
     }
 }
        internal void SendErrorResponse(HttpContextBase context, int httpStatusCode, int httpSubStatusCode, string httpStatusText, Action <HttpResponseBase> customResponseAction, bool closeConnection)
        {
            HttpResponseBase response = context.Response;

            response.Clear();
            response.StatusCode        = httpStatusCode;
            response.SubStatusCode     = httpSubStatusCode;
            response.StatusDescription = httpStatusText;
            if (customResponseAction != null)
            {
                customResponseAction(response);
            }
            if (closeConnection)
            {
                response.Close();
            }
            context.ApplicationInstance.CompleteRequest();
        }
Exemplo n.º 11
0
 /// <summary>
 /// 网页文件字节流下载
 /// </summary>
 /// <param name="response">Page.Request对象</param>
 /// <param name="bytes">字节流</param>
 /// <param name="fileName">文件名 如:pic.jpg file.mp4 file.csv</param>
 /// <returns>返回是否成功</returns>
 public static bool ResponseFile(HttpResponseBase response, byte[] bytes, string fileName)
 {
     try
     {
         response.AddHeader("Connection", "Keep-Alive");
         response.ContentType = "application/octet-stream";
         //通知浏览器下载文件而不是打开
         response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         response.BinaryWrite(bytes);
         response.Flush();
         response.End();
         response.Close();
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 12
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downloadPath"></param>
        /// <param name="server"></param>
        /// <param name="response"></param>
        /// <param name="fileName"></param>
        public static void DownloadFile(this string downloadPath, HttpServerUtilityBase server, HttpResponseBase response, string fileName)
        {
            if (!File.Exists(downloadPath))
            {
                Console.WriteLine("下载的资源不存在!");
                return;
            }
            FileStream iStream = null;

            byte[] buffer;

            try
            {
                var downloadFile = new FileInfo(downloadPath);
                //response.Clear();
                response.ClearHeaders();
                response.ContentType = "application/octet-stream";
                response.AppendHeader("Content-Disposition", "attachment;filename=" + server.UrlEncode(fileName + ".rar"));
                response.AppendHeader("Content-Length", downloadFile.Length.ToString());
                iStream = new FileStream(downloadPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var dataToRead = iStream.Length;
                buffer = new byte[dataToRead];
                iStream.Read(buffer, 0, buffer.Count());
                iStream.Close();
                response.BinaryWrite(buffer);
                response.Buffer = true;
                response.Flush();
                response.Close();
                response.End();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
            }
        }
Exemplo n.º 13
0
        public override void ExecuteResult(ControllerContext context)
        {
            string           fileName = _fileName;
            HttpResponseBase response = context.HttpContext.Response;

            if (File.Exists(_filePath))
            {
                FileStream fs         = null;
                byte[]     fileBuffer = new byte[10240000];//每次读取10240000字节大小的数据,10240000字节(b)=9.765625兆字节(mb)
                try
                {
                    using (fs = File.OpenRead(_filePath))
                    {
                        long totalLength = fs.Length;
                        response.ContentType = "application/octet-stream";
                        response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                        while (totalLength > 0 && response.IsClientConnected)       //持续传输文件
                        {
                            int length = fs.Read(fileBuffer, 0, fileBuffer.Length); //每次读取10240000个字节长度的内容
                            fs.Flush();
                            response.OutputStream.Write(fileBuffer, 0, length);     //写入到响应的输出流
                            response.Flush();                                       //刷新响应
                            totalLength = totalLength - length;
                        }
                        response.Close();//文件传输完毕,关闭相应流
                    }
                }
                catch (Exception ex)
                {
                    response.Write(ex.Message);
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();//最后记得关闭文件流
                    }
                }
            }
        }
        private static bool BinaryWriteDownload(HttpResponseBase response, string filePath, string fileName, Encoding encoding)
        {
            FileStream fileStream = null;

            try
            {
                return(ExecuteDownload(response, () =>
                {
                    using (fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        if (fileStream.Length >= MAXSIZE)
                        {
                            throw new Exception(SizeOver2GException);
                        }

                        response.AddHeader("Content-Length", fileStream.Length.ToString());

                        byte[] bytes = new byte[(int)fileStream.Length];
                        fileStream.Read(bytes, 0, bytes.Length);
                        fileStream.Close();

                        response.BinaryWrite(bytes);
                    }
                }, true, filePath, fileName, encoding));
            }
            catch
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                throw;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// End a HttpHandler Request
        /// </summary>
        public static void EndHttpHandlerRequest(this HttpResponseBase httpRes, bool skipHeaders = false, bool skipClose = false, bool closeOutputStream = false, Action <HttpResponseBase> afterHeaders = null)
        {
            if (!skipHeaders)
            {
                httpRes.ApplyGlobalResponseHeaders();
            }
            if (afterHeaders != null)
            {
                afterHeaders(httpRes);
            }
            if (closeOutputStream)
            {
                httpRes.CloseOutputStream();
            }
            else if (!skipClose)
            {
                httpRes.Close();
            }

            //skipHeaders used when Apache+mod_mono doesn't like:
            //response.OutputStream.Flush();
            //response.Close();
        }
Exemplo n.º 16
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            if (File.Exists(FileName))
            {
                FileStream fs         = null;
                byte[]     fileBuffer = new byte[BufferSize];//每次读取4096字节大小的数据
                try
                {
                    using (fs = File.OpenRead(FileName))
                    {
                        long totalLength = fs.Length;
                        response.ContentType = ContentType;
                        response.AddHeader("Content-Length", totalLength.ToString());
                        response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(FileName)));
                        while (totalLength > 0 && response.IsClientConnected)       //持续传输文件
                        {
                            int length = fs.Read(fileBuffer, 0, fileBuffer.Length); //每次读取4096个字节长度的内容
                            fs.Flush();
                            response.OutputStream.Write(fileBuffer, 0, length);     //写入到响应的输出流
                            response.Flush();                                       //刷新响应
                            totalLength = totalLength - length;
                        }
                        response.Close();//文件传输完毕,关闭相应流
                    }
                }
                catch (Exception ex)
                {
                    response.Write(ex.Message);
                }
                finally
                {
                    fs?.Close();//最后记得关闭文件流
                }
            }
        }
Exemplo n.º 17
0
        private ActionResult down(string path, string fileName)
        {
            string downPath = GetUploadPath(path);

            if (!System.IO.File.Exists(downPath))
            {
                return(Content("文件不存在!"));
            }
            if (CheckImage(downPath))
            {
                return(File(GetImageByte(downPath), @"image/jpeg"));
            }
            if (!fileName.Contains("."))
            {
                fileName += Path.GetExtension(downPath);
            }
            HttpResponseBase      response = this.HttpContext.Response;
            HttpServerUtilityBase server   = this.HttpContext.Server;

            response.Clear();
            response.Buffer = true;
            if (Request.Browser.Browser == "Firefox")
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            }
            else
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            }
            response.ContentType = CheckImage(downPath) ? "image/*" : "application/octet-stream";
            //response.AppendHeader("Content-Length", "attachment;filename=" + fileName);
            response.TransmitFile(downPath);
            response.Flush();
            response.Close();
            return(null);
        }
 public override void Close()
 {
     _response.Close();
 }
Exemplo n.º 19
0
        public void OpenStream()
        {
            System.IO.Stream iStream = null;
            byte[]           buffer  = new Byte[4096];
            int  length;
            long dataToRead;

            try
            {
                if (VDXApplicationSettings.IsLocalEnviornment())
                {
                    iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                                                       System.IO.FileAccess.Read, System.IO.FileShare.Read);
                }
                else
                {
                    VDXCloudBlob blobService = new VDXCloudBlob(this.filename);
                    iStream = blobService.ExecuteActionStream(VDXCloudAction.READ);
                }


                // Total bytes to read:
                dataToRead = iStream.Length;

                Response.AddHeader("Accept-Ranges", "bytes");
                Response.ContentType = "video/mp4";

                int startbyte = 0;

                if (!String.IsNullOrEmpty(Request.Headers["Range"]))
                {
                    string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startbyte = Int32.Parse(range[1]);
                    iStream.Seek(startbyte, SeekOrigin.Begin);

                    Response.StatusCode = 206;
                    Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startbyte, dataToRead - 1, dataToRead));
                }

                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = iStream.Read(buffer, 0, buffer.Length);

                        // Write the data to the current output stream.
                        Response.OutputStream.Write(buffer, 0, buffer.Length);
                        // Flush the data to the HTML output.
                        Response.Flush();

                        buffer     = new Byte[buffer.Length];
                        dataToRead = dataToRead - buffer.Length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (HttpException htx)
            {
                if (VDXApplicationSettings.IsLocalEnviornment())
                {
                    System.Diagnostics.Debug.WriteLine("HttpException: " + htx.Message);
                }
                else
                {
                    CloudLogError.ErrorMsg(htx.Message);
                }
            }
            catch (Exception ex)
            {
                if (VDXApplicationSettings.IsLocalEnviornment())
                {
                    System.Diagnostics.Debug.WriteLine("HttpException: " + ex.Message);
                }
                else
                {
                    CloudLogError.ErrorMsg(ex.Message);
                }
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                Response.Close();
            }
        }
 public override void Close()
 {
     proxiedResponse.Close();
 }
 public override void Close()
 {
     _httpResponseBase.Close();
 }
 private static void AbortConnection(HttpResponseBase httpResponseBase)
 {
     // TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available in 4.5
     httpResponseBase.Close();
 }
        /// <summary>
        /// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the
        /// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion.
        /// </summary>
        /// <param name="httpContextBase">The HTTP context base.</param>
        /// <param name="response">The response to convert.</param>
        /// <param name="request">The request (which will be disposed).</param>
        /// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/>
        /// including writing out any entity body.</returns>
        internal static Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request)
        {
            Contract.Assert(httpContextBase != null);
            Contract.Assert(response != null);
            Contract.Assert(request != null);

            HttpResponseBase httpResponseBase = httpContextBase.Response;

            httpResponseBase.StatusCode             = (int)response.StatusCode;
            httpResponseBase.StatusDescription      = response.ReasonPhrase;
            httpResponseBase.TrySkipIisCustomErrors = true;
            EnsureSuppressFormsAuthenticationRedirect(httpContextBase);
            CopyHeaders(response.Headers, httpContextBase);
            CacheControlHeaderValue cacheControl = response.Headers.CacheControl;

            // TODO 335085: Consider this when coming up with our caching story
            if (cacheControl == null)
            {
                // DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
                // However, we don't want requests to be cached by default.
                // If nobody set an explicit CacheControl then explicitly set to no-cache to override the
                // default behavior. This will cause the following response headers to be emitted:
                //     Cache-Control: no-cache
                //     Pragma: no-cache
                //     Expires: -1
                httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }

            Task responseTask = null;
            bool isBuffered   = false;

            if (response.Content != null)
            {
                CopyHeaders(response.Content.Headers, httpContextBase);

                // Select output buffering by the kind of content
                isBuffered = IsOutputBufferingNecessary(response.Content);
                httpResponseBase.BufferOutput = isBuffered;

                responseTask = response.Content.CopyToAsync(httpResponseBase.OutputStream);
            }
            else
            {
                responseTask = TaskHelpers.Completed();
            }

            return(responseTask
                   .Catch((info) =>
            {
                if (isBuffered)
                {
                    // Failure during the CopyToAsync needs to stop any partial content from
                    // reaching the client.  If it was during a buffered write, we will give
                    // them InternalServerError with zero-length content.
                    httpResponseBase.SuppressContent = true;
                    httpResponseBase.Clear();
                    httpResponseBase.ClearContent();
                    httpResponseBase.ClearHeaders();
                    httpResponseBase.StatusCode = (int)Net.HttpStatusCode.InternalServerError;
                }
                else
                {
                    // Any failure in non-buffered mode has already written out StatusCode and possibly content.
                    // This means the client will receive an OK but the content is incomplete.
                    // The proper action here is to abort the connection, but HttpResponse.Abort is a 4.5 feature.
                    // TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available
                    httpResponseBase.Close();
                }

                // We do not propagate any errors up, or we will get the
                // standard ASP.NET html page.   We want empty content or
                // a closed connection.
                return info.Handled();
            })
                   .Finally(
                       () =>
            {
                request.DisposeRequestResources();
                request.Dispose();
                response.Dispose();
            }));
        }
Exemplo n.º 24
0
 private static void AbortConnection(HttpResponseBase httpResponseBase)
 {
     // TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available in 4.5
     httpResponseBase.Close();
 }
Exemplo n.º 25
0
        /// <summary>
        /// 必须要有Content-Length和Content-Disposition以及ContentType
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="contentType"></param>
        /// <param name="Response"></param>
        public static void DownLoad(string filePath, string fileName, string contentType, HttpResponseBase Response, bool deleteAfterDownload = false)
        {
            //指定块大小
            long chunkSize = 204800;

            //建立一个200K的缓冲区
            byte[] buffer = new byte[chunkSize];
            //已读的字节数
            long       dataToRead = 0;
            FileStream stream     = null;

            try
            {
                //打开文件
                stream     = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                dataToRead = stream.Length;
                //添加Http头
                Response.ContentType = contentType;
                //解决,火狐浏览器下载时,中文名乱码
                if (HttpContext.Current.Request.Browser.Browser == "Firefox")
                {
                    //Response.AddHeader("Content-Disposition", "attachement;filename*=utf-8'zh_cn'" + fileName);
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                }
                else
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName).Replace("+", "%20"));
                }
                Response.AddHeader("Content-Length", dataToRead.ToString());
                while (dataToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        Response.Clear();
                        dataToRead -= length;
                    }
                    else
                    {
                        //防止client失去连接
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error:" + ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    if (deleteAfterDownload && File.Exists(filePath))
                    {
                        string path = Path.GetDirectoryName(filePath);
                        if (path.Length > RWUtility.GetResPath("").Length)
                        {
                            try { Directory.Delete(Path.GetDirectoryName(filePath), true); }
                            catch { }
                        }
                    }
                }
                Response.Close();
            }
        }