private static void SetupHttpContentDispositionForDownload(HttpResponseBase response, DownloadFileDescriptor descriptor, Encoding downloadContentEncoding) { response.ContentType = descriptor.MimeType; response.ContentEncoding = downloadContentEncoding; var filename = descriptor.ToStandardizedCsvDownloadFilename(); var contentDisposition = String.Format("attachment; filename=\"{0}\"", filename); response.AddHeader("Content-Disposition", contentDisposition); }
private void setResponseInfo() { doc.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Content\\Templates\\" + fileName); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.WriteFile(AppDomain.CurrentDomain.BaseDirectory + "Content\\Templates\\" + fileName); Response.End(); FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Content\\Templates\\" + fileName); fileInfo.Delete(); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpResponseBase response = filterContext.HttpContext.Response; var header = response.Headers["Content-Security-Policy"]; if (header == null) { response.AddHeader("Content-Security-Policy", "default-src 'self'; connect-src *; font-src *; frame-src *; img-src * data:; media-src *; object-src *; script-src * 'unsafe-inline' 'unsafe-eval'; style-src * 'unsafe-inline';"); } base.OnActionExecuting(filterContext); }
public static void ApplyGlobalResponseHeaders(this HttpResponseBase httpRes) { if (HostContext.Config == null) { return; } foreach (var globalResponseHeader in HostContext.Config.GlobalResponseHeaders) { httpRes.AddHeader(globalResponseHeader.Key, globalResponseHeader.Value); } }
public static void setGZipCompression_forAjaxRequests(HttpRequestBase request, HttpResponseBase response) { //based on code from http://geekswithblogs.net/rashid/archive/2007/09/15/Compress-Asp.net-Ajax-Web-Service-Response---Save-Bandwidth.aspx if (TMConfig.Current.TMSetup.EnableGZipForWebServices.isFalse()) { return; } if (request.Url.isNull() || request.Url.AbsolutePath.starts("/rest")) //disabled it for rest requests { return; } try { if (request.ContentType.lower().starts(new List <string> { "text/xml", "application/json" })) { string acceptEncoding = request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(acceptEncoding)) { acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture); if (acceptEncoding.Contains("gzip")) { response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); response.AddHeader("Content-encoding", "gzip"); } else if (acceptEncoding.Contains("deflate")) { response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); response.AddHeader("Content-encoding", "deflate"); } } } } catch (Exception ex) { ex.log("in enableGZipCompression_forAjaxRequests"); } }
public static bool CSV(string data, HttpResponseBase Response) { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv"); Response.Charset = ""; Response.ContentType = "application/text"; Response.Output.Write(data); Response.Flush(); Response.End(); return(true); }
static void SetHeaders(HttpResponseBase response, Result result) { if (!String.IsNullOrEmpty(result.Location)) { response.RedirectLocation = result.Location; } if (!String.IsNullOrEmpty(result.ContentLocation)) { response.AddHeader("Content-Location", result.ContentLocation); } }
public async Task ExportPorcentage(HttpResponseBase Response) { var porcentages = new List <ReportPorcentageModel>(); var complaints = await this.GetAllAsync(); var totalPerStatus = 0; var totalTickets = complaints.Data.Count(); var complaintsGrouped = complaints.Data.GroupBy(e => e.StatusId).ToList(); foreach (var item in complaintsGrouped) { var porcentage = new ReportPorcentageModel(); totalPerStatus = item.ToList().Count; decimal result = (decimal)totalPerStatus / (decimal)totalTickets; porcentage.StatusPorcentage = result * 100; porcentage.Status = item.FirstOrDefault().Status.Name; porcentages.Add(porcentage); } ExcelPackage pck = new ExcelPackage(); ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Tickets"); ws.Cells["A1"].Value = "Estado"; ws.Cells["B1"].Value = "Porcentaje"; int rowStart = 2; foreach (var item in porcentages) { ws.Cells[$"A{rowStart}"].Value = item.Status; ws.Cells[$"B{rowStart}"].Value = $"{item.StatusPorcentage:0.##}%"; rowStart++; } ws.Cells[$"A{complaints.Data.Count() + 1}"].Value = "Total"; ws.Cells[$"B{complaints.Data.Count() + 1}"].Value = complaints.Data.Count(); ws.Cells["A:AZ"].AutoFitColumns(); Response.Clear(); using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + $"Tickets-status-{DateTime.Now:MM-dd-yyyy-hh:mm-ss}" + ".xlsx"); pck.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }
public static void CreateExcelResponse(HttpResponseBase response, ExcelPackage excelPackage, string worksheetName) { if (Path.GetExtension(worksheetName) != ".xlsx") { worksheetName = string.Format("{0}.xlsx", worksheetName); } response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("content-disposition", string.Format("attachment; filename={0}", worksheetName)); response.BinaryWrite(excelPackage.GetAsByteArray()); response.End(); }
public override void Write(byte[] buffer, int offset, int count) { byte[] data = new byte[count]; Buffer.BlockCopy(buffer, offset, data, 0, count); var token = GetToken(new MemoryStream(data)); string clientToken = _request.Headers["If-None-Match"]; if (token != clientToken) { _response.AddHeader("ETag", token); _filter.Write(data, 0, count); } else { _response.SuppressContent = true; _response.StatusCode = 304; _response.StatusDescription = "Not Modified"; _response.AddHeader("Content-Length", "0"); } }
public static void DiplomProjectToWord(string fileName, DiplomProject work, HttpResponseBase response) { response.Clear(); response.Charset = "ru-ru"; response.HeaderEncoding = Encoding.UTF8; response.ContentEncoding = Encoding.UTF8; response.ContentType = "application/vnd.ms-word"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".doc"); CreateDoc(work, response); response.Flush(); response.End(); }
public void Export( ) { var employee = new Employee( ); var employeeFields = employee.GetType( ).GetProperties( ); var database = db.Employees.ToArray(); DataTable table = new DataTable( ); foreach (var field in employeeFields) { table.Columns.Add(field.Name, typeof(string)); } foreach (var item in database) { table.Rows.Add( item.Id, item.FirstName, item.MiddleInitial, item.LastName, item.HomePhoneNumber, item.CellPhoneNumber, item.OfficeExtension, item.TaxNumber, item.IsActive ); } table.Columns.Remove("Id"); var wbook = new XLWorkbook( ); wbook.Worksheets.Add(table, "EmployeeData"); wbook.Worksheets.First( ).Columns( ).AdjustToContents( ); HttpResponseBase httpResponse = Response; httpResponse.Clear( ); httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; httpResponse.AddHeader("content-disposition", "attachment;filename=\"EmployeeContactList" + DateTime.Now.ToShortDateString() + ".xlsx\""); using (MemoryStream memoryStream = new MemoryStream( )) { wbook.SaveAs(memoryStream); memoryStream.WriteTo(httpResponse.OutputStream); memoryStream.Close( ); } httpResponse.End( ); }
/// <summary> /// Append header to response /// </summary> /// <remarks> /// Seems like appendheader only works with IIS 7 /// </remarks> /// <param name="response"></param> /// <param name="httpResponseHeader"></param> /// <param name="headerValue"></param> public void AppendHeader(HttpResponseBase response, string httpResponseHeader, string headerValue) { switch (WebServerType) { case WebServerType.IIS7: response.AppendHeader(httpResponseHeader, headerValue); break; default: response.AddHeader(httpResponseHeader, headerValue); break; } }
protected override void WriteFile(HttpResponseBase response) { var outPutStream = response.OutputStream; response.AddHeader("content-disposition", "attachment; filename=" + "export.csv"); using (var streamWriter = new StreamWriter(outPutStream, System.Text.Encoding.UTF8)) using (var writer = new CsvWriter(streamWriter)) { //TODO : what if there are tons of records to write. //// without flush in between there may be hang. writer.WriteRecords(_data); } }
public static void PermanentRedirect(this HttpResponseBase response, string location) { if (null == response) { return; } response.Status = "301 Moved permanently"; response.StatusCode = 301; response.AddHeader( "Location", location); }
protected void ShowThumbnail(string path, int width, int height) { CheckPath(path); FileStream fs = new FileStream(FixPath(path), FileMode.Open); Bitmap img = new Bitmap(Bitmap.FromStream(fs)); fs.Close(); fs.Dispose(); int cropX = 0, cropY = 0; double imgRatio = (double)img.Width / (double)img.Height; if (height == 0) height = Convert.ToInt32(Math.Floor((double)width / imgRatio)); if (width > img.Width) width = img.Width; if (height > img.Height) height = img.Height; double cropRatio = (double)width / (double)height; int cropWidth = Convert.ToInt32(Math.Floor((double)img.Height * cropRatio)); int cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio)); if (cropWidth > img.Width) { cropWidth = img.Width; cropHeight = Convert.ToInt32(Math.Floor((double)cropWidth / cropRatio)); } if (cropHeight > img.Height) { cropHeight = img.Height; cropWidth = Convert.ToInt32(Math.Floor((double)cropHeight * cropRatio)); } if (cropWidth < img.Width) { cropX = Convert.ToInt32(Math.Floor((double)(img.Width - cropWidth) / 2)); } if (cropHeight < img.Height) { cropY = Convert.ToInt32(Math.Floor((double)(img.Height - cropHeight) / 2)); } Rectangle area = new Rectangle(cropX, cropY, cropWidth, cropHeight); Bitmap cropImg = img.Clone(area, System.Drawing.Imaging.PixelFormat.DontCare); img.Dispose(); Image.GetThumbnailImageAbort imgCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback); _r.AddHeader("Content-Type", MimeTypes.ImagePng); cropImg.GetThumbnailImage(width, height, imgCallback, IntPtr.Zero).Save(_r.OutputStream, ImageFormat.Png); _r.OutputStream.Close(); cropImg.Dispose(); }
public void ExportUser() { var isValidate = string.Empty; var keys = Request.Form.AllKeys; foreach (var key in keys) { isValidate = Request.Form[key]; } List <UserModel> list = SysService.GetUsers("", Boolean.Parse(isValidate), "", ""); StringBuilder sb = new StringBuilder(); sb.Append("<style type=\"text/css\">"); sb.Append("<!--"); sb.Append(".text"); sb.Append("{mso-style-parent:style0;"); sb.Append("font-size:10.0pt;"); sb.Append("font-family:\"Arial Unicode MS\", sans-serif;"); sb.Append("mso-font-charset:0;"); sb.Append(@"mso-number-format:\@;"); sb.Append("text-align:center;"); sb.Append("border:.5pt solid black;"); sb.Append("white-space:normal;}"); sb.Append("-->"); sb.Append("</style>"); sb.Append("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">"); sb.Append("<tr align=\"Center\" style=\"font-weight:bold;\">"); sb.Append("<td>用户ID</td><td>用户名</td><td>全名</td><td>邮箱</td><td>是否有效</td>"); sb.Append("</tr>"); foreach (var user in list) { string value = user.IsValid ? "是" : "否"; sb.Append("<tr align=\"Center\"><td>" + user.UserID + "</td><td>" + user.UserName + "</td><td>" + user.FullName + "</td><td>" + user.Email + "</td><td>" + value + "</td></tr>"); } sb.Append("</table>"); HttpResponseBase response = HttpContext.Response; response.Clear(); response.ContentType = "application/ms-excel"; if (HttpContext.Request.Browser.Type.StartsWith("Inter")) { response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("用户清单.xls", Encoding.GetEncoding("UTF-8"))); } response.AppendHeader("Content-Disposition", "attachment;filename=" + "用户清单.xls"); response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.AddHeader("Pragma", "public"); response.Write(sb.ToString()); response.End(); HttpContext.ApplicationInstance.CompleteRequest(); }
/// <summary> /// A HttpResponse extension method that disables the caching by setting Cacheability to HttpCacheability.NoCache, setting Expiration to /// DateTime.Now and add the pragma:no-cache header. /// </summary> /// <remarks> ebrown, 11/10/2010. </remarks> /// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are null. </exception> /// <param name="response"> The response to act on. </param> public static void DisableCaching(this HttpResponseBase response) { if (null == response) { throw new ArgumentNullException("response"); } var cache = response.Cache; cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.NoCache); cache.SetExpires(DateTime.Now); response.AddHeader("pragma", "no-cache"); }
public void Proccess(string nombre, List <object> rs, HttpResponseBase Response) { string filename = nombre; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename)); Response.Clear(); InitializeWorkbook(); GenerateData(rs); Response.BinaryWrite(WriteToStream().GetBuffer()); Response.End(); }
private void Export(PageFreshnessReportViewModel model, HttpResponseBase response) { using (var package = new ExcelPackage()) { AddWorksheet(package, "Top10FreshestPages", model.Top10FreshestPages); AddWorksheet(package, "Top10LeastFreshPages", model.Top10LeastFreshPages); response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("content-disposition", string.Format("attachment; filename=pages{0}.xlsx", DateTime.Now.ToString("yyyyMMdd"))); response.BinaryWrite(package.GetAsByteArray()); response.Flush(); response.End(); } }
/// <summary> /// 导出 /// </summary> public void DoExport() { if (this.FileName == null) { this.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); } Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.{1}", FileName, FileExt)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); ExcleExporter.Book.Write(ms); if (FileExt.Substring(0, 1) == ".") { FileExt = FileExt.Substring(1); } if (FileExt.ToLower() == "zip") { var path = Server.MapPath("~/Exports/"); Utils.CreateFolderIfNeeded(path); if (System.IO.File.Exists(path + FileName + ".xls")) { System.IO.File.Delete(path + FileName + ".xls"); } using (var fileStream = new System.IO.FileStream(path + FileName + ".xls", System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite)) { ms.Position = 0; ms.CopyTo(fileStream); // fileStream is not populated } this.Files.Add(path + FileName + ".xls"); if (System.IO.File.Exists(path + FileName + ".zip")) { System.IO.File.Delete(path + FileName + ".zip"); } ZipHelper.Zip(this.Files.ToArray(), path + FileName + ".zip"); Response.WriteFile(path + FileName + ".zip"); } else { Response.BinaryWrite(ms.ToArray()); } ExcleExporter.Book = null; ms.Close(); ms.Dispose(); }
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();//最后记得关闭文件流 } } }
/// <summary> /// If a range is specified, this will handle it. /// </summary> /// <param name="response"></param> /// <returns></returns> protected virtual bool HandleRange(HttpResponseBase response) { if (!Options.SupportByteRange) { return(false); } response.AddHeader("Accept-Ranges", "bytes"); var request = HttpContext.Current.Request; var range = ParseRange(request.Headers["Range"]); if (range == null) { return(false); } var fi = new FileInfo(FileName); var end = Math.Min(range.End, fi.Length - 1); // last byte is at 1 less than the length (0 based); var length = end - range.Start + 1; // the start is 0 based and end is inclusive. Eg, a range of 0-0 would be 1 byte. var ifrange = request.Headers["If-Range"]; if (ifrange.HasValue()) { if (mETag != ifrange) { return(false); } } response.StatusCode = 206; response.StatusDescription = "Partial Content"; response.AddHeader("Content-Range", "bytes {0}-{1}/{2}".Fmt(range.Start, end, fi.Length)); response.TransmitFile(FileName, range.Start, end); return(true); }
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(); }
/// <summary> /// 导出 /// </summary> public void DoExport() { if (this.FileName == null) { this.FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); Book.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.{1}", FileName, FileExt)); Response.BinaryWrite(ms.ToArray()); Book = null; ms.Close(); ms.Dispose(); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="location"></param> public static void RedirectPermanentWithoutEncodingURL(this HttpResponseBase response, string location) { if (HttpContext.Current.Request.Browser.Browser.ToLower().Equals("ie") && (HttpContext.Current.Request.Browser.MajorVersion == 6)) { response.RedirectPermanent(location); } else { response.Clear(); response.StatusCode = 301; response.Status = "301 Moved Permanently"; response.AddHeader("Location", location); response.End(); } }
public void Enforce(HttpResponseBase response) { if (!AppLogic.AppConfigBool("ContentSecurityPolicy.Enabled")) { return; } foreach (var header in Headers) { if (!response.Headers.AllKeys.Contains(header.Key)) { response.AddHeader(header.Key, header.Value); } } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals (context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("JSON GET is not allowed"); } HttpResponseBase response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType; if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } else { response.AddHeader("Content-Encoding", "gzip"); } if (this.Data == null) { return; } using (var memStream = new MemoryStream()) { using (var zipStream = new GZipStream(memStream, CompressionMode.Compress, true)) { using (var streamWriter = new StreamWriter(zipStream)) { using (var jsonWriter = new JsonTextWriter(streamWriter)) { var jsonSerializer = JsonSerializer.Create(this.Settings); jsonSerializer.Serialize(jsonWriter, this.Data); } } } response.BinaryWrite(memStream.ToArray()); } }
public void ToExcel(HttpResponseBase Response, object clientsList) { var grid = new System.Web.UI.WebControls.GridView(); grid.DataSource = clientsList; grid.DataBind(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=FileName.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); }
public void ToExcel_XLSX <T>(HttpResponseBase Response, List <T> clientsList) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Lotes"); workSheet.Cells[1, 1].LoadFromCollection(clientsList, true); using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=ListagemLotes.xlsx"); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }