예제 #1
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            try
            {
                response.ClearHeaders();
                response.ClearContent();
            }
            catch { }

            response.TrySkipIisCustomErrors = true;

            if (this.HttpStatus != default(HttpStatusCode))
            {
                response.StatusCode = (int)this.HttpStatus;
            }

            if (String.IsNullOrEmpty(this.ContentType))
            {
                response.ContentType = "text/plain";
            }
            else
            {
                response.ContentType = this.ContentType;
            }

            this.WriteMessage(response);
        }
예제 #2
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ClearHeaders();
            response.AppendHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
            response.AppendHeader("Pragma", "no-cache");
            response.AppendHeader("Expires", "-1");
            HttpCachePolicyBase cache = response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);

            if (string.IsNullOrEmpty(this.Filename))
            {
                this.Filename = "output.xls";
            }
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment;filename=" + this.Filename);

            if (this.ContentEncoding == null)
            {
                this.ContentEncoding = System.Text.Encoding.GetEncoding("Shift_JIS");
                //this.ContentEncoding = System.Text.Encoding.UTF8;
            }
            response.ContentEncoding = this.ContentEncoding;

            response.BinaryWrite(Data.GetBuffer());
        }
 static void SetEmptyErrorResponse(HttpResponseBase httpResponseBase)
 {
     httpResponseBase.Clear();
     httpResponseBase.ClearHeaders();
     httpResponseBase.StatusCode      = (int)HttpStatusCode.InternalServerError;
     httpResponseBase.SuppressContent = true;
 }
예제 #4
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // get rendered HTML from view
            string html     = ViewRenderer.RenderViewToString(context, ViewName, Model);
            var    cssFiles = CssHelper.GetAllCssPaths(html);
            //html = ClearHtmlStrategy.Clear(html);
            // generate the PDF content from HTML
            var pageConfig = PageConfig != null ? PageConfig : PageSize.A4;

            byte[]           content            = HtmlToPdfRenderer.Render(html, cssFiles, pageConfig);
            var              contentDisposition = IsAttachment ? "attachement" : "inline";
            HttpResponseBase response           = context.HttpContext.Response;

            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = "application/pdf";
            response.AppendHeader("Content-Disposition", $"{contentDisposition};filename={Filename}.pdf");
            response.AddHeader("Content-Length", content.Length.ToString());
            response.BinaryWrite(content);
            response.OutputStream.Flush();
            response.OutputStream.Close();
            response.End();
        }
예제 #5
0
        public override void OnResultExecuting(ResultExecutingContext ctx)
        {
            HttpRequestBase  request  = ctx.RequestContext.HttpContext.Request;
            HttpResponseBase response = ctx.RequestContext.HttpContext.Response;

            if (ctx.Result == null || !(ctx.Result is FileContentResult))
            {
                base.OnResultExecuting(ctx);
                return;
            }

            var result = ctx.Result as FileContentResult;

            var eTag = Convert.ToBase64String(new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(result.FileContents));

            response.ClearHeaders();
            response.Cache.SetSlidingExpiration(true);
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetETag(eTag);
            response.Cache.SetMaxAge(TimeSpan.FromSeconds(_maxAgeInSeconds));

            if (request.Headers["If-None-Match"] != null && request.Headers["If-None-Match"] == eTag)
            {
                response.StatusCode        = 304;
                response.StatusDescription = "Not Modified";
                ctx.Cancel = true;
            }
            else
            {
                base.OnResultExecuting(ctx);
            }
        }
예제 #6
0
 private static void SetResponseState(HttpResponseBase response)
 {
     response.ClearHeaders();
     response.Clear();
     response.Expires = 0;
     response.Buffer  = true;
 }
예제 #7
0
 private static void SetupHttpHeadersForDownloadImpl(HttpResponseBase response, DownloadFileDescriptor descriptor, Encoding downloadContentEncoding)
 {
     // Leaving this ClearHeaders since it is IMMEDIDATELY followed by a line replacing the SetExpires below. -- SLG 10/2/2012
     response.ClearHeaders();
     SetupHttpContentDispositionForDownload(response, descriptor, downloadContentEncoding);
     SetupHttpCachingHeaders(response);
 }
        private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)
        {
            httpResponseBase.Clear();

            // Despite what the documentation indicates, calling Clear on its own doesn't fully clear the headers.
            httpResponseBase.ClearHeaders();
        }
 /// <summary>
 /// Exports the chart to the specified HttpResponse object. This method
 /// is preferred over WriteToStream() because it handles clearing the
 /// output stream and setting the HTTP reponse headers.
 /// </summary>
 /// <param name="httpResponse"></param>
 public void WriteToHttpResponse(HttpResponseBase httpResponse)
 {
     httpResponse.ClearContent();
     httpResponse.ClearHeaders();
     httpResponse.ContentType = this.ContentType;
     httpResponse.AddHeader("Content-Disposition", this.ContentDisposition);
     WriteToStream(httpResponse.OutputStream);
 }
예제 #10
0
        //pre:  must but in page you don't want the browser back to him again && make if statment with Session check
        //Post: This is used to clear Cache And Heade (To Handl back button in browser)
        //ToCall: just call the object and action and write (Response) inside functions ==> myLibrary.PreventBackButtonBrowser(Response);
        public void PreventBackButtonBrowser(HttpResponseBase response)
        {
            response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetNoStore();

            response.ClearHeaders();
            response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
            response.AddHeader("Pragma", "no-cache");
        }
예제 #11
0
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;

            try
            {
                response.ClearHeaders();
                response.ClearContent();
            }
            catch { }

            response.TrySkipIisCustomErrors = true;

            if (this.Resource == null)
            {
                response.ContentType = "text/plain";
                response.StatusCode  = (int)HttpStatusCode.NotFound;
                response.Write(response.Status);
                return;
            }

            HttpContext httpContext = HttpContext.Current;

            // check if client has cached copy
            ETag etag = new HashETag(this.Resource.Hash);

            if (etag.HandleETag(httpContext, HttpCacheability.ServerAndPrivate, this.IsDebug))
            {
                return;
            }

            if (String.IsNullOrEmpty(this.Resource.ContentType))
            {
                response.ContentType = "text/plain";
            }
            else
            {
                response.ContentType = this.Resource.ContentType;
            }

            // this helps IE determine the Content-Type
            // http://tools.ietf.org/html/rfc2183#section-2.3
            ContentDisposition disposition = new ContentDisposition
            {
                Inline   = !this.IsAttachment,
                FileName =
                    String.IsNullOrEmpty(this.Filename) ?
                    Path.GetFileNameWithoutExtension(this.ResourcePath) + '.' + this.Resource.FileExtension :
                    this.Filename
            };

            response.AddHeader("Content-Disposition", disposition.ToString());

            ResourceHandler.WriteResponse(httpContext, this.Resource, this.IsDebug);
        }
예제 #12
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            response.ClearHeaders();
            response.AppendHeader("Cache-Control", "private, no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0");
            response.AppendHeader("Pragma", "no-cache");
            response.AppendHeader("Expires", "-1");
            HttpCachePolicyBase cache = response.Cache;

            cache.SetCacheability(HttpCacheability.NoCache);

            if (string.IsNullOrEmpty(this.Filename))
            {
                this.Filename = "data.csv";
            }
            response.ContentType = "application/octet-stream";
            response.AddHeader("Content-Disposition", "attachment;filename=" + this.Filename);

            if (this.ContentEncoding == null)
            {
                this.ContentEncoding = System.Text.Encoding.GetEncoding("Shift_JIS");
                //this.ContentEncoding = System.Text.Encoding.UTF8;
            }
            response.ContentEncoding = this.ContentEncoding;

            if (this.Data != null)
            {
                //見出し行を出力。
                OutputHeader(response);

                //各行のデータを出力。
                foreach (object item in this.Data)
                {
                    OutputLine(response, item);
                }
            }
            else
            {
                //見出し行を出力。
                OutputHeaderFromDataTable(response);

                //各行のデータを出力。
                foreach (DataRow dr in this.dataTable.Rows)
                {
                    OutputLineFromDataTable(response, dr);
                }
            }
        }
예제 #13
0
        private void MakeExcel(System.Data.DataTable data)
        {
            string   FileName = "report" + DateTime.Today.ToShortDateString();
            FileInfo f        = new FileInfo(Server.MapPath("Downloads") + string.Format("\\{0}.xlsx", FileName));

            if (f.Exists)
            {
                f.Delete();
            }
            // delete the file if it already exist.

            HttpResponseBase response = HttpContext.Response;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();
            response.Charset = Encoding.UTF8.WebName;
            response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
            response.AddHeader("Content-Type", "application/Excel");
            response.ContentType = "application/vnd.xlsx";
            //response.AddHeader("Content-Length", file.Length.ToString());
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            response.Write("<Table border='1' bgColor='#ffffff' " +
                           "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
                           "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");


            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    DataGrid dg = new DataGrid();
                    dg.DataSource = data;
                    dg.DataBind();
                    dg.RenderControl(htw);
                    response.Write(sw.ToString());
                    dg.Dispose();
                    data.Dispose();
                    response.SetCookie(new HttpCookie("fileDownload", "true")
                    {
                        Path = "/"
                    });
                    //response.Redirect("ReportPage");
                    response.End();
                }
            }
        }
예제 #14
0
 private static void WriteCsvFile(HttpResponseBase Response, StringBuilder sb, string sExportedFileName)
 {
     Response.Clear();
     Response.ClearContent();
     Response.ClearHeaders();
     Response.Buffer      = true;
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("content-disposition",
                        "attachment;filename=" + sExportedFileName + ".csv");
     // Response.ContentType = "application/text";
     Response.ContentEncoding = Encoding.GetEncoding("windows-1256");
     Response.Output.Write(sb.ToString());
     Response.Flush();
     Response.End();
 }
예제 #15
0
        public static Tuple <Stream, string, string> GetExportPdf <T>(List <T> result, HttpServerUtilityBase server, HttpResponseBase response)
        {
            ReportDocument rd   = new ReportDocument();
            string         name = typeof(T).Name;

            rd.Load(Path.Combine(server.MapPath("~/Reports"), name + "Report.rpt"));
            rd.SetDataSource(result);
            response.Buffer = false;
            response.ClearContent();
            response.ClearHeaders();
            Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

            stream.Seek(0, SeekOrigin.Begin);
            return(new Tuple <Stream, string, string>(stream, "application/pdf", name + "Report.pdf"));
        }
예제 #16
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();
        }
예제 #17
0
파일: WebHelper.cs 프로젝트: liskying/ShCss
        /// <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();
                }
            }
        }
 public override void ClearHeaders()
 {
     _response.ClearHeaders();
 }
        private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)
        {
            httpResponseBase.Clear();

            // Despite what the documentation indicates, calling Clear on its own doesn't fully clear the headers.
            httpResponseBase.ClearHeaders();
        }
예제 #20
0
 /// <summary>
 /// Adds the proper HTTP headers for a file download.  <see>
 ///                                                        <cref>SitkaGlobalBase.AddCachingHeaders</cref>
 ///                                                    </see>
 /// </summary>
 public static void SetupHttpHeadersForDownload(HttpResponseBase response)
 {
     // Leaving this ClearHeaders since it is IMMEDIDATELY followed by a line replacing the SetExpires below. -- SLG 10/2/2012
     response.ClearHeaders();
     SetupHttpCachingHeaders(response);
 }
 public override void ClearHeaders()
 {
     _httpResponseBase.ClearHeaders();
 }
 public override void ClearHeaders()
 {
     proxiedResponse.ClearHeaders();
 }
 private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)
 {
     httpResponseBase.Clear();
     httpResponseBase.ClearHeaders();
 }
        /// <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();
            }));
        }
예제 #25
0
 public void Clear()
 {
     _response.ClearHeaders();
     _headers.Clear();
 }
예제 #26
0
 private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)
 {
     httpResponseBase.Clear();
     httpResponseBase.ClearHeaders();
 }