public AppendHeader ( string name, string value ) : void | ||
name | string | |
value | string | |
return | void |
/// <summary> /// 导入数据,保存文档 /// </summary> /// <param name="tab"></param> /// <param name="fileName"></param> /// <param name="typeName"></param> /// <param name="styleText"></param> private void TableExport(System.Web.UI.HtmlControls.HtmlGenericControl tab, string fileName, string typeName, bool isFireFox) { System.Web.HttpResponse httpResponse = _InvokePage.Response; httpResponse.Clear(); httpResponse.Buffer = true; httpResponse.Charset = "gb2312";// "GB2312"; //Response.Charset = "UTF-8"; httpResponse.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>"); if (isFireFox == true) { fileName = "\"" + fileName + "\""; httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); } else { httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString()); } httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); httpResponse.ContentType = typeName; _InvokePage.EnableViewState = false; StringWriter tw = new StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); tab.RenderControl(hw); // httpResponse.Write(styleText); httpResponse.Write(tw.ToString()); httpResponse.End(); }
private int StreamFile(string FilePath, string DownloadAs) { DownloadAs = DownloadAs.Replace(" ", "_"); System.IO.FileInfo objFile = new System.IO.FileInfo(FilePath); if (!objFile.Exists) { return(0); } System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("Content-Disposition", "attachment; filename=" + DownloadAs); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); string strContentType; strContentType = "application/octet-stream"; objResponse.ContentType = strContentType; WriteFile(objFile.FullName); objResponse.Flush(); objResponse.Close(); return(1); }
public void Process(HttpResponse response) { response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r")); response.AppendHeader("ETag", serverFingerprint.ETag); response.AppendHeader("Cache-Control", "private, max-age=0"); if (!string.IsNullOrEmpty(fileName)) { response.AppendHeader( "Content-Disposition", "attachment; filename=\"" + Path.GetFileName(fileName) + "\""); } if (!string.IsNullOrEmpty(type)) { response.ContentType = type; } else if (!string.IsNullOrEmpty(fileName)) { var mimeType = GetMimeType(fileName); response.ContentType = mimeType; } else { response.ContentType = "application/octetstream"; } fileTransfer.Download(response.OutputStream); }
private static void DownloadFile(string FileLoc) { FileInfo objFile = new FileInfo(FileLoc); System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; string filename = objFile.Name; if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE ") > 0) { filename = HttpUtility.UrlEncode(filename); } if (objFile.Exists) { objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); objResponse.ContentType = GetContentType(objFile.Extension.Replace(".", "")); if (objResponse.ContentType.Contains("x-shockwave-flash") || objResponse.ContentType.Contains("video")) { objResponse.AddHeader("Content-Disposition", "inline;filename=\"" + filename + "\""); } else { objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + filename + "\""); } WriteFile(objFile.FullName); objResponse.Flush(); objResponse.End(); } }
// Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer = true; if (FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek(0, SeekOrigin.Begin); XmlDocument xsl = new XmlDocument(); xsl.Load(stream); //XslTransform xslTran = new XslTransform(); //xslTran.Load(new XmlTextReader(stream), null, null); //System.IO.StringWriter sw = new System.IO.StringWriter(); //xslTran.Transform(xmlDoc, null, sw, null); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); XslCompiledTransform t = new XslCompiledTransform(); t.Load((IXPathNavigable)xsl, null, null); t.Transform((IXPathNavigable)xmlDoc, xtw); //Writeout the Content response.Write(sw.ToString()); sw.Close(); xtw.Close(); writer.Close(); stream.Close(); response.End(); sw.Dispose(); stream.Dispose(); } catch (ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch (Exception Ex) { throw Ex; } }
public void Process(HttpResponse response) { response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r")); response.AppendHeader("ETag", serverFingerprint.ETag); response.AppendHeader("Cache-Control", "private, max-age=0"); response.BinaryWrite(content); }
public static void AddCompressionFilter(HttpRequest request, HttpResponse response) { // load encodings from header QValueList encodings = new QValueList(request.Headers["Accept-Encoding"]); // get the types we can handle, can be accepted and // in the defined client preference QValue preferred = encodings.FindPreferred("gzip", "deflate", "identity"); // if none of the preferred values were found, but the // client can accept wildcard encodings, we'll default // to Gzip. if (preferred.IsEmpty && encodings.AcceptWildcard && encodings.Find("gzip").IsEmpty) preferred = new QValue("gzip"); // handle the preferred encoding switch (preferred.Name) { case "gzip": response.AppendHeader("Content-Encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); break; case "deflate": response.AppendHeader("Content-Encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); break; case "identity": default: break; } }
public void Process(HttpResponse response) { response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r")); response.AppendHeader("ETag", serverFingerprint.ETag); response.AppendHeader("Cache-Control", "private, max-age=0"); response.ContentType = MimeType.Json.ContentType; response.Write(jsonFragment); }
public static void ToExcel(DataSet dsInput, string filename, HttpResponse response) { var excelXml = GetExcelXml(dsInput, filename); response.Clear(); response.AppendHeader("Content-Type", "application/vnd.ms-excel"); response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpContext.Current.Server.UrlEncode(filename) + "\""); response.Write(excelXml); response.Flush(); response.End(); }
// Function : Export_with_XSLT_Web // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName // Purpose : Exports dataset into CSV / Excel format private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers response.Clear(); response.Buffer = true; if (FormatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } //response.BinaryWrite(Encoding.Unicode.GetPreamble()); // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream( ); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush( ); stream.Seek(0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); //dsExport.WriteXml("Data.xml"); XslTransform xslTran = new XslTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new System.IO.StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); //xslTran.Transform(System.Web.HttpContext.Current.Server.MapPath("Data.xml"), null, sw, null); //Writeout the Content response.Write(sw.ToString()); sw.Close(); writer.Close(); stream.Close(); response.End(); } catch (ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch (Exception Ex) { throw Ex; } }
// Exports dataset into CSV / Excel format private void ExportXSLT(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers objHttpResponse.Clear(); objHttpResponse.Buffer = true; if (FormatType == ExportFormat.CSV) { objHttpResponse.ContentType = "text/csv"; objHttpResponse.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { objHttpResponse.ContentType = "application/vnd.ms-excel"; objHttpResponse.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); //dsExport.WriteXml("Data.xml"); XslTransform xslTran = new XslTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new System.IO.StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); //Writeout the Content objHttpResponse.Write(sw.ToString()); sw.Close(); writer.Close(); stream.Close(); objHttpResponse.End(); } catch (ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch (Exception Ex) { ErrorLog.WriteErrorLog("DB2Excel-ExportDetails", Ex); } }
private static void ResponseWrite(string Result, string FileName, string ContentType) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; byte[] lstByte = System.Text.Encoding.UTF8.GetBytes(Result); Response.ClearHeaders(); Response.ClearContent(); Response.ContentType = string.Format("{0}; charset=utf-8", ContentType); Response.AppendHeader("Content-disposition", string.Format("attachment; filename=\"{0}\"", FileName)); Response.AppendHeader("Content-Length", lstByte.Length.ToString()); Response.BinaryWrite(lstByte); Response.Flush(); Response.End(); }
private static void SetResponseHeader(HttpResponse response, string buildVersion) { if (WebVersionConfiguration.Settings.SendResponseHeader) { response.AppendHeader("X-Web-Version", buildVersion); } }
/// <summary> /// 导出EXCEL(HTML格式的) /// </summary> /// <param name="ds">要导出的DataSet</param> /// <param name="fileName"></param> public static void CreateEXCEL(DataSet ds, string fileName) { System.Web.UI.WebControls.DataGrid dg = new DataGrid(); dg.DataSource = ds; dg.DataBind(); for (int i = 0; i < dg.Items.Count; i++) { for (int j = 0; j < dg.Items[i].Cells.Count; j++) { dg.Items[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@"); } } System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); System.Web.UI.WebControls.DataGrid DG = dg; DG.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); }
/// <summary> /// 将DataTable中的数据导出到指定的Excel文件中 /// </summary> /// <param name="page">Web页面对象</param> /// <param name="tab">包含被导出数据的DataTable对象</param> /// <param name="fileName">Excel文件的名称</param> public static bool Export(System.Web.UI.Page page, System.Data.DataTable tab, string fileName) { bool returnvalue = false; System.Web.HttpResponse httpResponse = page.Response; System.Web.UI.WebControls.DataGrid dataGrid = new System.Web.UI.WebControls.DataGrid(); dataGrid.DataSource = tab.DefaultView; dataGrid.AllowPaging = false; dataGrid.HeaderStyle.BackColor = System.Drawing.Color.BurlyWood; dataGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; dataGrid.HeaderStyle.Font.Bold = true; dataGrid.DataBind(); httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //filename="*.xls"; httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); httpResponse.ContentType = "application/ms-excel"; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); dataGrid.RenderControl(hw); string filePath = System.Web.HttpContext.Current.Server.MapPath("/BasicInfo/temp/") + fileName; System.IO.StreamWriter sw = System.IO.File.CreateText(filePath); sw.Write(tw.ToString()); sw.Close(); sw.Dispose(); returnvalue = DownFile(httpResponse, fileName, filePath); httpResponse.End(); return(returnvalue); }
public static void GZipEncodePage(HttpRequest Request, HttpResponse Response) { if (!IsGZipSupported(Request)) return; string AcceptEncoding = Request.Headers["Accept-Encoding"]; if (AcceptEncoding.Contains("gzip")) { Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress); Response.AppendHeader("Content-Encoding", "gzip"); } else { Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress); Response.AppendHeader("Content-Encoding", "deflate"); } }
private void AddHeadersToEnable403Cacheing(HttpResponse response) { var browser = HttpContext.Current.Request.Browser; if (browser.IsBrowser("IE") && (browser.MajorVersion <= 6)) { // Turn off caching due to issues with IE 6.0 response.Cache.SetCacheability(HttpCacheability.NoCache); response.Cache.SetNoStore(); } else { response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r")); response.AppendHeader("ETag", serverFingerprint.ETag); response.AppendHeader("Cache-Control", "no-store"); } }
//public static void DisableMasterPageStamp(Page page) //{ // Validate.NotNull(page, "page"); // if (page.Master != null) // { // Control ctrl = page.Master.FindControl(DoubleSubmitStamp.MasterPageControlName); // if (ctrl != null) // ((DoubleSubmitStamp) ctrl).RenderStamp = false; // } //} public static void MakePageExpired(HttpResponse response) { Validate.NotNull(response, "response"); response.Expires = 0; response.Cache.SetNoStore(); response.AppendHeader("Pragma", "no-cache"); }
public void prepareExcelFile(string name, System.Web.HttpResponse resp) { resp.ClearContent(); resp.ClearHeaders(); resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"); resp.ContentType = "application/vnd.ms-excel"; }
/// <summary> /// ����IHttpHandler���� /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { Request = context.Request; Response = context.Response; Session = context.Session; VerifyImage dt_verifyImage = new VerifyImage(); dt_verifyImage._Random = new Random(); dt_verifyImage._Code = dt_verifyImage.GetRandomCode(); dt_verifyImage.BackColor = ColorTranslator.FromHtml("#edf8fe"); Session["SystemCode"] = dt_verifyImage._Code; ///����û�л��� Response.Buffer = true; Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1); Response.Expires = 0; Response.CacheControl = "no-cache"; Response.AppendHeader("Pragma", "No-Cache"); Bitmap objBitmap = dt_verifyImage.GetVerifyImage(); objBitmap.Save(Response.OutputStream, ImageFormat.Gif); if (null != objBitmap) objBitmap.Dispose(); Response.ContentType = "image/gif"; Response.Write(Response.OutputStream); }
private static void MapResponseToHttpResponse(Response response, HttpResponse httpResponse) { response.Headers.ForEach(header => httpResponse.AppendHeader(header.Key, header.Value)); httpResponse.StatusCode = response.StatusCode; httpResponse.ContentType = response.ContentType; response.Contents.Invoke(httpResponse.OutputStream); }
public static void ExportToExcel(System.Web.HttpResponse Response, string datos) { Response.Clear(); Response.Write(datos); Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", "attachment; filename=Informe.xls"); Response.End(); }
public static void EncodeStreamAndAppendResponseHeaders(HttpResponse response, string acceptEncoding) { if (acceptEncoding == null) return; var preferredEncoding = ParsePreferredEncoding(acceptEncoding); if (preferredEncoding == null) return; response.AppendHeader("Content-Encoding", preferredEncoding); response.AppendHeader("Vary", "Accept-Encoding"); if (preferredEncoding == "deflate") { response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress, true); } if (preferredEncoding == "gzip") { response.Filter = new GZipStream(response.Filter, CompressionMode.Compress, true); } }
public static void DownloadFile(System.Web.HttpResponse Response, string filePath) { Byte[] file = File.ReadAllBytes(filePath); File.Delete(filePath); Response.ContentType = "documento/" + Path.GetExtension(filePath).ToUpper(); Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath)); Response.BinaryWrite(file); Response.End(); }
public void SetupResponse(System.Web.HttpResponse response, string fileName) { response.ClearHeaders(); response.Clear(); response.Cache.SetCacheability(System.Web.HttpCacheability.Private); response.Cache.SetMaxAge(new TimeSpan(0)); response.Cache.SetExpires(new DateTime(0)); response.Cache.SetNoServerCaching(); response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (fileName + "\""))); }
/// <summary> /// Sends the file to the response with content-length header /// Works with all types of files, not image specific /// </summary> /// <param name="response"></param> /// <param name="file"></param> /// <param name="mimetype"></param> private static void SendToResponse(HttpResponse response, byte[] fileContent, DateTime lastWriteTime, string mimetype) { response.ClearHeaders(); setCacheHeaders(response); response.Cache.SetLastModified(lastWriteTime); // to avoid rounding problems with header (no millisecs there) response.ContentType = mimetype; response.AppendHeader("Content-Length", fileContent.Length.ToString()); response.BinaryWrite(fileContent); response.End(); }
private void ExportwithXSLT(DataSet dsExport, string[] sHeaders, string[] sFileds, string FormatType, string FileName) { try { response.Clear(); response.Buffer = true; if (FormatType == ExportFormat.CSV.ToString()) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); XslTransform xslTran = new XslTransform(); xslTran.Load(new XmlTextReader(stream), null, null); System.IO.StringWriter sw = new System.IO.StringWriter(); xslTran.Transform(xmlDoc, null, sw, null); response.Write(sw.ToString()); sw.Close(); writer.Close(); stream.Close(); response.End(); } catch (ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch (Exception Ex) { throw Ex; } }
public virtual void Export(ContentItem item, ExportOptions options, HttpResponse response) { response.ContentType = GetContentType(); response.AppendHeader("Content-Disposition", "attachment;filename=" + GetExportFilename(item)); using (var output = GetTextWriter(response)) { Export(item, options, output); output.Flush(); } response.End(); }
/// <summary> /// Sends the file to the response with content-length header. will check last-writetime for sending modified header /// </summary> /// <param name="Response"></param> /// <param name="file"></param> /// <param name="mimetype"></param> /// <remarks>Works with all types of files, not image specific</remarks> public void SendToResponse(HttpResponse Response, FileInfo file, string mimetype) { Response.ClearHeaders(); setCacheHeaders(Response); //Response.Cache.SetETag("\"999ed196eeb0cc1:9\""); Response.Cache.SetLastModified(file.LastWriteTime); Response.ContentType = mimetype; Response.AppendHeader("Content-Length", file.Length.ToString()); Response.WriteFile(file.FullName); Response.End(); }
public void Genratewordtext(string str_text, string filename) { try { string temp_path = ""; string strFileName = filename + ".doc"; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AppendHeader("Content-Type", "application/msword"); response.AppendHeader("Content-disposition", "attachment; filename=" + strFileName); response.Write(str_text); response.End(); } catch (Exception EX) { //return ""; throw EX; } }
/// <summary> /// 把DataTable导出为Word文件 /// </summary> /// <param name="page">Page</param> /// <param name="fileName">Word文件名(不包括后缀*.doc)</param> /// <param name="dtbl">将要被导出的DataTable对象</param> /// <returns></returns> public static bool DataTableToWord(System.Web.HttpResponse response, string fileName, DataTable dtbl) { response.Clear(); response.Buffer = true; response.Charset = "UTF-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".doc"); response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.ContentType = "application/ms-word"; //page.EnableViewState = false; response.Write(DataTableToHtmlTable(dtbl)); response.End(); return(true); }
public void DownloadFile() { string filePath = Server.MapPath("~/Files_SelfEmployment/App/") + "Test" + ".pdf"; //This is used to get the current response. System.Web.HttpResponse res = GetHttpResponse(); res.Clear(); res.AppendHeader("content-disposition", "attachment; filename=" + filePath); res.ContentType = "application/octet-stream"; res.WriteFile(filePath); res.Flush(); res.End(); }
public void Render(HttpResponse response) { string serializedItems = ToString(); response.Clear(); var calendarName = _calendarName.Replace(',', ' '); response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}.ics", HttpUtility.UrlPathEncode(calendarName))); response.ContentType = "text/calendar"; response.Write(serializedItems); }
/// <summary> /// 下载文件 /// </summary> /// <param name="FileLoc">文件真实路径</param> /// <param name="FileName">显示文件名</param> public static void DownloadFile(string FileLoc, string FileName) { System.IO.FileInfo objFile = new System.IO.FileInfo(FileLoc); System.Web.HttpResponse objResponse = System.Web.HttpContext.Current.Response; string truefilename = objFile.Name; if (HttpContext.Current.Request.UserAgent.IndexOf("; MSIE ") > 0) { truefilename = HttpUtility.UrlEncode(truefilename, System.Text.Encoding.UTF8); } if (objFile.Exists) { objResponse.ClearContent(); objResponse.ClearHeaders(); objResponse.AppendHeader("content-disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(FileName) + "\""); objResponse.AppendHeader("Content-Length", objFile.Length.ToString()); objResponse.ContentType = GetContentType(objFile.Extension.Replace(".", "")); WriteFile(objFile.FullName); objResponse.Flush(); objResponse.End(); } }
/// <summary> /// 把内存流(文件)发送到客户端 /// </summary> /// <param name="fileName">文件名称</param> /// <param name="ms">文件流</param> /// <param name="response">响应客户端对象</param> public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null) { encoding = encoding ?? Encoding.UTF8; if (ms != null && !string.IsNullOrEmpty(fileName)) { HttpContext context = System.Web.HttpContext.Current; System.Web.HttpResponse response = context.Response; response.Clear(); response.AppendHeader("Content-Type", "application/octet-stream"); response.Charset = encoding.BodyName;// "utf-8"; //if (AppConfig. !context.Request.UserAgent.Contains("Firefox") && !context.Request.UserAgent.Contains("Chrome")) //{ fileName = HttpUtility.UrlEncode(fileName, encoding); //} response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); response.BinaryWrite(ms.GetBuffer()); ms.Close(); ms = null; response.Flush(); response.End(); } }
private static void RenderToResponseStream(HttpResponse response, XmlBaseController baseController) { // save script timeout var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) HttpContext.Current.Server.ScriptTimeout = int.MaxValue; response.ContentType = baseController.ContentType; response.AppendHeader("content-disposition", "inline; filename=" + baseController.FileName); baseController.Render(response.OutputStream); response.Flush(); // reset script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; }
private static List<string> RespHeaders = new List<string>() { "ETag", "Content-Disposition", "Content-Encoding", "Cache-Control" };//, "Expires", "Pragma"}; protected virtual void ProxyResponse(HttpResponse target, HttpWebResponse source) { target.StatusCode = (int)source.StatusCode; target.Charset = source.CharacterSet; target.ContentType = source.ContentType; foreach (string H in RespHeaders) { var V = source.Headers[H]; if (V != null) target.AppendHeader(H, V); } using (var RespStream = source.GetResponseStream()) RespStream.CopyTo(target.OutputStream); }
/// <summary> /// 将workbook从浏览器端下载 /// </summary> /// <param name="workbook">Workbook</param> /// <param name="response">HttpResponse</param> /// <param name="filename">保存的文件名</param> public static void Download(Workbook workbook, System.Web.HttpResponse response, string filename = null) { if (string.IsNullOrEmpty(filename)) { filename = DateTime.Now.ToString("yyyyMMdd_hhMMssfff") + ".xls"; } response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + filename); response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/ms-excel"; response.BinaryWrite(workbook.SaveToStream().ToArray()); response.End(); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AppendHeader("content-length", stream.Length.ToString()); byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); // Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); // Display an error on the webpage. System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page; page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true); return(false); } }
public virtual void sendResponse(HttpResponse response) { response.ContentType = "text/xml"; if (compressResponse) { response.Filter = new GZipStream(response.Filter, CompressionMode.Compress, true); response.AppendHeader("Content-encoding", "gzip"); } using(StreamWriter responseWriter = new StreamWriter(response.OutputStream, Encoding.UTF8)) { XmlDocument responseDocument = createResponseDocument(); if (attachSignature) signDocument(responseDocument); responseDocument.Save(responseWriter); responseDocument = null; } }
protected void imgFileEdmilson_Click(object sender, ImageClickEventArgs e) { string jogos = "jogosByConfig.txt"; string pathJogos = Server.MapPath(Path.Combine("~", jogos)); // Prompts user to save file System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.AddHeader("Content-Length", pathJogos.Length.ToString()); response.ContentType = "text/plain"; response.AppendHeader("Content-Disposition", "attachment; filename=" + jogos + ";"); response.TransmitFile(pathJogos); response.End(); HttpContext.Current.ApplicationInstance.CompleteRequest(); }
public void ProcessRequest(HttpContext context) { string sPath = string.Empty; string sNomArchivo = oWeb.GetData("sNomArchivo"); string sNumContrato = oWeb.GetData("sNumContrato"); System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; sPath = HttpContext.Current.Server.MapPath("..\\rps_licenciatariosmattel") + "\\" + sNomArchivo; oResponse.ContentType = "application/octet-stream"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=" + sNomArchivo); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
private void descargarArchivo(string nombreArchivo, string dirCompleto) { try { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.ContentType = "application/octet-stream"; response.AppendHeader("Content-Disposition", "attachment; filename=" + nombreArchivo + ";"); //response.TransmitFile(Server.MapPath("~/File/001.jpg")); response.TransmitFile(dirCompleto); HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event. } catch (Exception ex) { Response.Write("<script>alert('" + ex.ToString() + "')</script>"); } }
internal static void ProcessRequestInternal(HttpContext context, string overrideVirtualPath) { HttpRequest request = context.Request; HttpResponse response = context.Response; if (!ProcessRequestForNonMapPathBasedVirtualFile(request, response, overrideVirtualPath)) { string path; string physicalPath; if (overrideVirtualPath == null) { path = request.Path; physicalPath = request.PhysicalPath; } else { path = overrideVirtualPath; physicalPath = request.MapPath(overrideVirtualPath); } FileInfo info = GetFileInfo(path, physicalPath, response); DateTime lastModified = new DateTime(info.LastWriteTime.Year, info.LastWriteTime.Month, info.LastWriteTime.Day, info.LastWriteTime.Hour, info.LastWriteTime.Minute, info.LastWriteTime.Second, 0); DateTime now = DateTime.Now; if (lastModified > now) { lastModified = new DateTime(now.Ticks - (now.Ticks % 0x989680L)); } string etag = GenerateETag(context, lastModified, now); long length = info.Length; string str4 = request.Headers["Range"]; if (!StringUtil.StringStartsWithIgnoreCase(str4, "bytes") || !ProcessRangeRequest(context, physicalPath, length, str4, etag, lastModified)) { SendFile(physicalPath, 0L, length, length, context); response.ContentType = MimeMapping.GetMimeMapping(physicalPath); response.AppendHeader("Accept-Ranges", "bytes"); response.AddFileDependency(physicalPath); response.Cache.SetIgnoreRangeRequests(); response.Cache.SetExpires(DateTime.Now.AddDays(1.0)); response.Cache.SetLastModified(lastModified); response.Cache.SetETag(etag); response.Cache.SetCacheability(HttpCacheability.Public); } } }
private static void ShowSource(HttpResponse response, int moduleId, int portalId, Hashtable settings) { if (response == null) throw new ArgumentNullException("response"); var scriptTimeOut = HttpContext.Current.Server.ScriptTimeout; // temporarily set script timeout to large value ( this value is only applicable when application is not running in Debug mode ) HttpContext.Current.Server.ScriptTimeout = int.MaxValue; response.ContentType = "xml|text/xml"; response.AppendHeader("content-disposition", "inline; filename=" + "datasource.xml"); using (var writer = XmlWriter.Create(response.OutputStream)) { var providerName = settings[Setting.SourceProvider].DefaultIfNullOrEmpty(); if (providerName != string.Empty) writer.WriteNode(XmlDataProvider.Instance(providerName).Load(moduleId, portalId, settings), false); writer.Flush(); } response.Flush(); // reset script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; string sPath = string.Empty; sPath = sPath + "\\\\srvdebt03\\Comun\\Mattel Europa\\Base.bak"; oResponse.ContentType = "application/pdf"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=Base.bak"); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
/// <summary> /// 输入下载的文件 /// </summary> /// <param name="Response">用于输出的对像</param> /// <param name="fileName">输出文件名</param> /// <param name="fullPath">输出路径</param> private static bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath) { try { Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=UTF-8"); System.IO.FileStream fs = System.IO.File.OpenRead(fullPath); long fLen = fs.Length; int size = 102400; //每100K同时下载数据 byte[] readData = new byte[size]; //指定缓冲区的大小 if (size > fLen) { size = Convert.ToInt32(fLen); } long fPos = 0; bool isEnd = false; while (!isEnd) { if ((fPos + size) > fLen) { size = Convert.ToInt32(fLen - fPos); readData = new byte[size]; isEnd = true; } fs.Read(readData, 0, size);//读入一个压缩块 Response.BinaryWrite(readData); fPos += size; } fs.Close(); fs.Dispose(); System.IO.File.Delete(fullPath); return(true); } catch { return(false); } }
public static void SetValue(HttpResponse response, string type, string key, string value) { try { switch (type) { case "cookie": HttpCookie cookie = new HttpCookie(key, value); response.Cookies.Set(cookie); break; case "headers": response.AppendHeader(key, value); break; default: break; } } catch (Exception e) { Debug.WriteLine("Error: " + e.Message); } }
public static void Exportar(string nombreArchivo, IList titulos, IList propiedades, IList elementos, HttpResponse response, string tituloPrincipal) { string pathArchivo = ConfigurationManager.AppSettings["PATH_TEMP"] + nombreArchivo; FileInfo archivo = new FileInfo(pathArchivo); StreamWriter handlerArchivo = archivo.CreateText(); handlerArchivo.WriteLine(tituloPrincipal); // Escribir encabezado string linea = ""; foreach (string titulo in titulos) { linea += "=CONCATENAR(\"\";\"" + titulo + "\";\"\")\t"; } handlerArchivo.WriteLine(linea); // Escribir contenido foreach (object elemento in elementos) { linea = ""; foreach (string propiedad in propiedades) { linea += "=CONCATENAR(\"\";\"" + ReflectionUtils.GetProperty(elemento, propiedad) + "\";\"\")\t"; } handlerArchivo.WriteLine(linea); } // Genero la salida handlerArchivo.Close(); response.AppendHeader("content-disposition", "attachment; filename=" + nombreArchivo); response.ContentType = "application / msexcel"; response.WriteFile(pathArchivo); response.End(); }
/// <summary> /// 输出一个图片到输出流 /// </summary> /// <param name="Response"></param> /// <param name="b"></param> /// <param name="img_format"></param> public static void OutPutImage(System.Web.HttpResponse Response, Bitmap b, System.Drawing.Imaging.ImageFormat img_format, TimeSpan?freshness, int quality_num) { Response.Clear(); Response.BufferOutput = false; //提高效率 if (freshness.HasValue) //要缓冲 { DateTime now = DateTime.Now; Response.Cache.SetExpires(now.Add((TimeSpan)freshness)); Response.Cache.SetMaxAge((TimeSpan)freshness); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(true); } else { Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)); //特别注意 Response.Cache.SetCacheability(HttpCacheability.NoCache); //特别注意 Response.AppendHeader(" Pragma", "No-Cache"); //特别注意 } ImageCodecInfo myImageCodecInfo = ZImage.GetEncoder(img_format); System.Drawing.Imaging.Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; myEncoder = System.Drawing.Imaging.Encoder.Quality; myEncoderParameters = new EncoderParameters(1); myEncoderParameter = new EncoderParameter(myEncoder, (long)quality_num);//quality_num + "L"); // 0-100 myEncoderParameters.Param[0] = myEncoderParameter; Response.ContentType = GetContentTypeFromImageFormat(img_format); b.Save(Response.OutputStream, myImageCodecInfo, myEncoderParameters); HttpContext.Current.ApplicationInstance.CompleteRequest(); }
/// <summary> /// 导出文本 /// </summary> /// <param name="exportStr">导出的文本</param> /// <param name="fileName">导出的文件名</param> private static void RenderToDaoChu(string exportStr, string fileName) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; if ("" == exportStr) { return; } Response.Clear(); Response.Buffer = true; Response.Charset = "GB2312"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312"); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文 Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); oHtmlTextWriter.Write(exportStr); Response.Write(oStringWriter.ToString()); Response.End(); }
/// <summary> /// Sets No Chache to Cliente browser /// </summary> /// <param name="response"></param> public static void SetNoCacheNoStore(HttpResponse response) { response.ClearHeaders(); response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1 response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); response.Cache.SetCacheability(HttpCacheability.Private); response.Cache.SetNoStore(); }
private static bool CheckForTabExternalForwardOrRedirect(HttpContext context, ref UrlAction result, HttpResponse response, FriendlyUrlSettings settings, Guid parentTraceId) { bool finished = false; HttpRequest request = null; if (context != null) { request = context.Request; } try { //check for external forwarding or a permanent redirect request //592 : check for permanent redirect (823 : moved location from 'checkForRedirects') if (result.TabId > -1 && result.PortalId > -1 && (settings.ForwardExternalUrlsType != DNNPageForwardType.NoForward || result.Reason == RedirectReason.Tab_Permanent_Redirect)) { bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLower().Contains("&ctl=tab")); //594 : do not redirect settings pages for external urls if (allowRedirect) { TabInfo tab; allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); if (allowRedirect) { //772 : not redirecting file type Urls when requested. bool permanentRedirect = false; string redirectUrl = null; string cleanPath = null; bool doRedirect = false; switch (tab.TabType) { case TabType.File: //have to fudge in a portal settings object for this to work - shortcoming of LinkClick URl generation var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); if (context != null) { context.Items.Add("PortalSettings", portalSettings); result.Reason = RedirectReason.File_Url; string fileUrl = Globals.LinkClick(tab.Url, tab.TabID, -1); context.Items.Remove("PortalSettings"); //take back out again, because it will be done further downstream //do a check to make sure we're not repeating the Url again, because the tabid is set but we don't want to touch //a linkclick url if (!result.OriginalPathNoAlias.EndsWith(HttpUtility.UrlDecode(fileUrl), true, CultureInfo.InvariantCulture)) { redirectUrl = fileUrl; } } if (redirectUrl != null) { doRedirect = true; } break; case TabType.Url: result.Reason = RedirectReason.Tab_External_Url; redirectUrl = tab.Url; if (redirectUrl != null) { doRedirect = true; if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) { result.Action = ActionType.Redirect301; result.Reason = RedirectReason.Tab_External_Url; } else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) { result.Action = ActionType.Redirect302; result.Reason = RedirectReason.Tab_External_Url; } } break; case TabType.Tab: // if a tabType.tab is specified, it's either an external url or a permanent redirect //get the redirect path of the specific tab, as long as we have a valid request to work from if (request != null) { //get the rewrite or requested path in a clean format, suitable for input to the friendly url provider cleanPath = RewriteController.GetRewriteOrRequestedPath(result, request.Url); //727 prevent redirectLoop with do301 in querystring if (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302) { cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, request.QueryString); } //get the redirect Url from the friendly url provider using the tab, path and settings redirectUrl = RedirectController.GetTabRedirectUrl(tab, settings, cleanPath, result, out permanentRedirect, parentTraceId); } //check to make sure there isn't a blank redirect Url if (redirectUrl == null) { //problem : no redirect Url to redirect to //solution : cancel the redirect string message = "Permanent Redirect chosen for Tab " + tab.TabPath.Replace("//", "/") + " but forwarding Url was not valid"; RedirectController.CancelRedirect(ref result, context, settings, message); } else { //if there was a redirect Url, set the redirect action and set the type of redirect going to use doRedirect = true; if (permanentRedirect) { result.Action = ActionType.Redirect301; result.Reason = RedirectReason.Tab_Permanent_Redirect; //should be already set, anyway result.RewritePath = cleanPath; } else { //not a permanent redirect, check if the page forwarding is set if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) { result.Action = ActionType.Redirect301; result.Reason = RedirectReason.Tab_External_Url; } else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) { result.Action = ActionType.Redirect302; result.Reason = RedirectReason.Tab_External_Url; } } } break; default: //only concern here is if permanent redirect is requested, but there is no external url specified if (result.Reason == RedirectReason.Tab_Permanent_Redirect) { bool permRedirect = tab.PermanentRedirect; if (permRedirect) { //problem : permanent redirect marked, but no forwarding url supplied //solution : cancel redirect string message = "Permanent Redirect chosen for Tab " + tab.TabPath.Replace("//", "/") + " but no forwarding Url Supplied"; RedirectController.CancelRedirect(ref result, context, settings, message); } } break; } //do the redirect we have specified if (doRedirect && (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) { result.FinalUrl = redirectUrl; if (result.Action == ActionType.Redirect301) { if (response != null) { //perform a 301 redirect to the external url of the tab response.Status = "301 Moved Permanently"; response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); response.AddHeader("Location", result.FinalUrl); response.End(); } } else { if (result.Action == ActionType.Redirect302) { if (response != null) { //perform a 301 redirect to the external url of the tab response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); response.Redirect(result.FinalUrl); } } } finished = true; } } } } } catch (ThreadAbortException) { //do nothing, a threadAbortException will have occured from using a server.transfer or response.redirect within the code block. This is the highest //level try/catch block, so we handle it here. } return finished; }
private void HandleBadRequest(string message, HttpResponse response) { response.StatusCode = 400; response.ContentType = "text/plain"; response.AppendHeader("Content-Length", message.Length.ToString()); response.Write(message); response.Flush(); }
/// <summary> /// Clears response header whitout harming http-compression header /// </summary> public static void ClearHeadersButSaveEncoding(HttpResponse response) { HttpCookie cookie = response.Cookies[Consts.FrontEndPresentation.HttpCompressor]; string encode = cookie[Consts.FrontEndPresentation.HttpCompressEncoding]; response.ClearHeaders(); if (string.IsNullOrEmpty(encode)) return; response.AppendHeader("Content-Encoding", encode); }
protected virtual void ApplyHeadersToResponse(HttpResponse response) { if (_webData != null && _webData.ResponseInfo.Headers != null) { WebHeaderCollection coll = _webData.ResponseInfo.Headers; for (int i = 0; i < coll.Count; i++) { try { response.AppendHeader(coll.GetKey(i), coll[i]); } catch { } } } }
public void ProcessRequest(HttpContext context) { string sPath = string.Empty; string sNomFactura = oWeb.GetData("sNomFactura"); string sNumContrato = oWeb.GetData("sNumContrato"); DBConn oConn = new DBConn(); if (oConn.Open()) { cContratos oContratos = new cContratos(ref oConn); oContratos.NumContrato = sNumContrato; DataTable dtContrato = oContratos.Get(); if (dtContrato != null) { if (dtContrato.Rows.Count > 0) { cCliente oCliente = new cCliente(ref oConn); oCliente.NkeyCliente = dtContrato.Rows[0]["nkey_cliente"].ToString(); DataTable dtCliente = oCliente.Get(); if (dtCliente != null) { if (dtCliente.Rows.Count > 0) { sPath = dtCliente.Rows[0]["pathsdocscaneados"].ToString() + "\\" + dtCliente.Rows[0]["direcarchivos"].ToString(); } } dtContrato = null; } } } oConn.Close(); System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response; sPath = sPath + "\\" + sNomFactura + ".pdf"; oResponse.ContentType = "application/pdf"; oResponse.AppendHeader("Content-Disposition", "attachment; filename=" + sNomFactura + ".pdf"); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = new FileStream(sPath, FileMode.Open, FileAccess.Read); do { if (oResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); oResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); oResponse.Flush(); oResponse.End(); } finally { if (download != null) { download.Close(); } } }
public void AppendHeader(HttpResponse response) { response.AppendHeader("Content-Encoding", EncodingName); }
private void ReturnMessage(RtmptConnection connection, ByteBuffer data, HttpResponse response) { response.StatusCode = 200; response.ClearHeaders(); response.AppendHeader("Connection", "Keep-Alive"); int contentLength = data.Limit + 1; response.AppendHeader("Content-Length", contentLength.ToString()); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType.RTMPT; response.Write((char)connection.PollingDelay); byte[] buffer = data.ToArray(); response.OutputStream.Write(buffer, 0, buffer.Length); response.Flush(); }
private void ReturnMessage(byte message, HttpResponse response) { response.StatusCode = 200; response.ClearHeaders(); response.AppendHeader("Connection", "Keep-Alive"); response.AppendHeader("Content-Length", "1"); response.Cache.SetCacheability(HttpCacheability.NoCache); response.ContentType = ContentType.RTMPT; response.Write((char)message); response.Flush(); }