public override void ExecuteResult(ControllerContext context) { Guard.ArgumentNotNull(context, "context"); HttpResponseBase response = context.HttpContext.Response; response.Clear(); response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.RedirectLocation = Url; }
public async Task ExportServiceRate(HttpResponseBase Response) { var rates = await _serviceRateRepository.GetAllAsync(); var rateGrouped = rates.Data.GroupBy(e => e.Rate).ToList(); var totalRates = rates.Data.Count(); var porcentages = new List <ServiceRatePortenageModel>(); var totalPerRate = 0; foreach (var item in rateGrouped) { totalPerRate = item.ToList().Count; decimal result = (decimal)totalPerRate / (decimal)totalRates; var porcentage = new ServiceRatePortenageModel(); porcentage.Rate = Enum.GetName(typeof(EnumRate), item.FirstOrDefault().Rate); porcentage.RatePorcentage = result * 100; porcentages.Add(porcentage); } ExcelPackage pck = new ExcelPackage(); ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Tickets"); ws.Cells["A1"].Value = "Puntuacion"; ws.Cells["B1"].Value = "Porcentaje"; int rowStart = 2; foreach (var item in porcentages) { ws.Cells[$"A{rowStart}"].Value = item.Rate; ws.Cells[$"B{rowStart}"].Value = $"{item.RatePorcentage.ToString("0.##")}%"; rowStart++; } ws.Cells[$"A{rates.Data.Count() + 1}"].Value = "Total"; ws.Cells[$"B{rates.Data.Count() + 1}"].Value = rates.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-rate-{DateTime.Now.ToString("MM-dd-yyyy-hh:mm-ss")}" + ".xlsx"); pck.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }
protected override void WriteFile(HttpResponseBase response) { response.Clear(); response.AppendHeader("content-disposition", "attachment; filename=" + _fName); response.ContentType = "application/octet-stream;charset=utf-8"; response.TransmitFile(_fileSystemPath); //response.WriteFile(_fileSystemPath); //byte[] buffer = System.IO.File.ReadAllBytes(_fileSystemPath); //string check = Encoding.UTF8.GetString(buffer); //response.BinaryWrite(buffer); }
public static void ToExcel(DataSet dsInput, string filename, HttpResponseBase response) { var excelXml = GetExcelXml(dsInput, filename); response.Clear(); response.AppendHeader("Content-Type", "application/vnd.ms-excel"); response.AppendHeader("Content-disposition", "attachment; filename=" + filename); response.Write(excelXml); response.Flush(); response.End(); }
/// <summary> /// Send a 401 response /// <param name="returnUrl"> /// For passing the returnUrl in order to force a refresh of the /// current page in case the cancel button in the Login popup has been clicked</param> /// </summary> public void Send401(string returnUrl) { _response.AppendHeader("Connection", "close"); _response.StatusCode = 0x191; _response.Clear(); _response.Write("Login cancelled. Please wait to be redirected..."); // A Refresh header needs to be added in order to keep the application going after the // Windows Authentication Login popup is cancelled: _response.AddHeader("Refresh", "0; url=" + returnUrl); _response.End(); }
public override void ExecuteResult(ControllerContext context) { Guard.ArgumentNotNull(context, "context"); HttpResponseBase response = context.HttpContext.Response; var urlHelper = new UrlHelper(context.RequestContext); var url = urlHelper.Action(this.ActionName, this.ControllerName, this.RouteValues); response.Clear(); response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.RedirectLocation = url; }
private void WriteHtmlResponse(Exception exceptionWritingView, Controller controller) { log.Fatal(Error.FatalException, exceptionWritingView); HttpResponseBase response = controller.Response; ErrorViewModel model = helper.GetErrorViewModel(controller.RouteData, exceptionWritingView); string html = GetHtmlResponse(model); response.Clear(); response.ContentType = Constants.HtmlContentType; response.Write(html); }
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 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(); } }
private void GenerateThumbnailFromStream(Stream imgStream, HttpResponseBase Response, string imgExt) { if (imgStream == null) { return; } var imgFull = Image.FromStream(imgStream); imgStream.Close(); imgStream.Dispose(); var curHeight = imgFull.Height; var curWidth = imgFull.Width; imgHeight = curHeight; imgWidth = curWidth; if (imgMaxHeight.HasValue || imgMaxWidth.HasValue) { if (curHeight > imgMaxHeight || curWidth > imgMaxWidth) { if (imgMaxHeight.HasValue && imgMaxWidth.HasValue) { if (imgMaxHeight > imgMaxWidth) { imgHeight = (imgMaxWidth.Value * curHeight) / curWidth; imgWidth = imgMaxWidth.Value; } else { imgWidth = (imgMaxHeight.Value * curWidth) / curHeight; imgHeight = imgMaxHeight.Value; } } else if (imgMaxHeight.HasValue) { imgWidth = (imgMaxHeight.Value * curWidth) / curHeight; imgHeight = imgMaxHeight.Value; } else { imgHeight = (imgMaxWidth.Value * curHeight) / curWidth; imgWidth = imgMaxWidth.Value; } } } var img = GenerateThumbnail(imgFull, imgExt); Response.Clear(); Response.ContentType = "image/" + (imgExt.Length >= 4 ? imgExt.Substring(1) : "png"); Response.BinaryWrite(img); Response.End(); }
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); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } StringWriter sw = new StringWriter(); JsonSerializer serializer = JsonSerializer.Create( new JsonSerializerSettings { //Converters = new JsonConverter[] { new Newtonsoft.Json.Converters.IsoDateTimeConverter() }, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, //PreserveReferencesHandling = PreserveReferencesHandling.Objects } ); using (JsonWriter jsonWriter = new JsonTextWriter(sw)) { jsonWriter.Formatting = Formatting.Indented; if (!NotUIFriendlySerialize) { serializer.Serialize(jsonWriter, this); } else { serializer.Serialize(jsonWriter, data); } } HttpResponseBase response = context.HttpContext.Response; // 清除在返回前已经设置好的标头信息,这样后面的跳转才不会报错 response.Clear(); //设置输出缓冲 response.BufferOutput = true; //if (!response.IsRequestBeingRedirected)//在跳转之前做判断,防止重复 //{ // response.ContentType = "application/json"; //} if (callbackName.IsNullOrEmpty()) { response.Write(sw.ToString()); } else { response.Write(callbackName + "(" + sw.ToString() + ")"); } }
public static void Export <T>(List <T> data, HttpResponseBase response, string excelName) { Workbook workbook = new Workbook(); Worksheet sheet = (Worksheet)workbook.Worksheets[0]; //为标题设置样式 Style styleTitle = workbook.Styles[workbook.Styles.Add()]; //新增样式 styleTitle.HorizontalAlignment = TextAlignmentType.Center; //文字居中 styleTitle.Font.Name = "宋体"; //文字字体 styleTitle.Font.Size = 18; //文字大小 styleTitle.Font.IsBold = true; //粗体 var objType = typeof(T); PropertyInfo[] properties = objType.GetProperties(); //生成行1 标题行 sheet.Cells.Merge(0, 0, 1, properties.Length); //合并单元格 sheet.Cells[0, 0].PutValue(excelName); //填写内容 sheet.Cells[0, 0].SetStyle(styleTitle); sheet.Cells.SetRowHeight(0, 20); int i = 2; int j = 0; foreach (PropertyInfo propInfo in properties) { var attrName = propInfo.Name; DescriptionAttribute attr = (DescriptionAttribute)Attribute.GetCustomAttribute(propInfo, typeof(DescriptionAttribute)); if (attr != null) { attrName = attr.Description; sheet.Cells[i, j].PutValue(attrName); int ii = i + 1; foreach (var d in data) { sheet.Cells[ii, j].PutValue(propInfo.GetValue(d, null)); ii++; } sheet.Cells.SetColumnWidth(j, 15); j++; } } response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", excelName)); response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/ms-excel"; response.BinaryWrite(workbook.SaveToStream().ToArray()); 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( ); }
public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; response.Clear(); response.ContentType = "text/csv"; response.AddHeader("content-disposition", "attachment; filename=QueryResults.csv"); response.AddHeader("content-length", Encoding.UTF8.GetByteCount(RawCsv).ToString()); response.AddHeader("Pragma", "public"); response.Write(RawCsv); response.Flush(); response.Close(); }
/// <summary> /// 下载文件 /// </summary> /// <param name="context">HttpContext</param> /// <param name="filePath">要下载的文件的完整路径</param> /// <param name="downloadName">下载时要显示的文件名</param> /// <param name="isDelete">下载后是否删除文件</param> /// <param name="bts">文件的byte</param> public void FileDonwLoad(HttpRequestBase Request, HttpResponseBase Response, string downloadName, bool isDelete = false, byte[] bts = null, string filePath = null) { //以字符流的形式下载文件 byte[] bytes; if (bts == null) { FileStream fs = new FileStream(filePath, FileMode.Open); bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); //读取完成后删除 if (isDelete) { File.Delete(filePath); } } else { bytes = bts; } //下载文件 Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8"); if (!string.IsNullOrEmpty(filePath) && filePath.Contains(".xls")) { Response.ContentType = "application/ms-excel"; } else { Response.ContentType = "application/octet-stream"; } if (Request.UserAgent.ToLower().IndexOf("msie") > -1) { downloadName = HttpUtility.UrlPathEncode(downloadName); } if (Request.UserAgent.ToLower().IndexOf("firefox") > -1) { Response.AddHeader("Content-Disposition", "attachment;filename=\"" + downloadName + "\""); } else { Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName); } Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.BinaryWrite(bytes); Response.Flush(); //context.Response.End(); //清空以免缓存影响下次下载 Response.Clear(); }
public override void OnResultExecuted(ResultExecutedContext filterContext) { if (filterContext.Result.GetType() == typeof(JsonResult)) { HttpResponseBase response = filterContext.HttpContext.Response; JsonResult result = filterContext.Result as JsonResult; response.Clear(); string jsonData = JsonConvert.SerializeObject(result.Data, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }); response.Write(jsonData); } }
public void DownloadDir(string path) { path = FixPath(path); if (!Directory.Exists(path)) { throw new Exception(LangRes("E_CreateArchive")); } var dirName = new FileInfo(path).Name; var tmpZip = _context.Server.MapPath("../tmp/" + dirName + ".zip"); if (System.IO.File.Exists(tmpZip)) { System.IO.File.Delete(tmpZip); } ZipFile.CreateFromDirectory(path, tmpZip, CompressionLevel.Fastest, true); _r.Clear(); _r.Headers.Add("Content-Disposition", "attachment; filename=\"" + dirName + ".zip\""); _r.ContentType = "application/force-download"; _r.TransmitFile(tmpZip); _r.Flush(); System.IO.File.Delete(tmpZip); _r.End(); }
public override void ExecuteResult(ControllerContext context) { HttpResponseBase response = context.HttpContext.Response; string attachment = "attachment; filename=ExecutionPlan.sqlplan"; response.Clear(); response.ContentType = "text/xml"; response.AddHeader("content-disposition", attachment); response.AddHeader("Pragma", "public"); response.Write(plan); response.Flush(); response.Close(); }
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(); }
public static void ReturnError(HttpResponseBase response, int httpStatusCode, string msg) { response.Clear(); response.StatusCode = httpStatusCode; response.Write(msg); try { response.End(); } catch (NullReferenceException) { // TODO: If request running in HttpSimulator, the added ApplicationInstance seems to cause NRE here, so just ignore it. } }
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(); }
public void Execute() { if (_context.Response.StatusCode == 404) { _response.Clear(); var rd = new RouteData(); rd.Values["controller"] = "Errors"; rd.Values["action"] = "NotFound"; IController c = new ErrorsController(); c.Execute(new RequestContext(_context, rd)); } }
/// <summary> /// DataSet直接导出Excel,此方法会把DataSet的数据用Excel打开,再自己手动去保存到确切的位置 /// </summary> /// <param name="ds">要导出Excel的DataSet</param> /// <returns></returns> public static void DoExportForDataSet(DataSet ds, List <string> sheetslist, HttpResponseBase response, string excelName) { Workbook workbook = new Workbook(); workbook.Worksheets.Clear(); foreach (string s in sheetslist) { workbook.Worksheets.Add(s); } if (ds != null) { int t = 0; foreach (DataTable dt in ds.Tables) { Worksheet sheet = (Worksheet)workbook.Worksheets[t]; var colIndex = "A"; int cnt = dt.Rows.Count; int columncnt = dt.Columns.Count; //写入excel for (int j = 0; j < dt.Columns.Count; j++) { sheet.Cells[colIndex + 1].PutValue(dt.Columns[j].ColumnName); colIndex = ((char)(colIndex[0] + 1)).ToString(); } colIndex = "A"; // 获取具体数据 for (int i = 0; i < dt.Columns.Count; i++) { int k = 2; for (int j = 0; j < dt.Rows.Count; j++) { sheet.Cells[colIndex + k].PutValue(dt.Rows[j][i]); k++; } colIndex = ((char)(colIndex[0] + 1)).ToString(); } t++; } } response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/ms-excel"; response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", excelName)); response.BinaryWrite(workbook.SaveToStream().ToArray()); response.End(); }
public static void ExportToExcel <T>(HttpResponseBase response, string myPageName, List <ColumnInfo> columns, List <T> list) { string FileName = myPageName + ".xls"; response.Clear(); response.Buffer = true; response.Charset = "utf-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName); string ss = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); response.ContentType = "application/ms-excel"; StringBuilder builder = new StringBuilder(); builder.Append("<html><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>") .Append("<body><table width='100%' border='1'><tr bgcolor='gray' style='COLOR: white'>"); for (int k = 0; k < columns.Count; k++) { builder.Append("<td align='center'>").Append(columns[k].ColumnDisplayName).Append("</td>"); } builder.Append("</tr>"); for (int i = 0; i < list.Count; i++) { //Dictionary<string, string> dic = list[i]; T obj = list[i]; builder.Append("<tr>"); for (int j = 0; j < columns.Count; j++) { ColumnInfo column = columns[j]; string columnType = column.ColumnType; string columnName = column.ColumnName; object tmpValue = typeof(T).GetProperty(columnName).GetValue(obj, null); string value = tmpValue == null ? "" : tmpValue.ToString(); if (columnType != null && columnType.Equals("date")) { value = value.Split(new char[] { ' ' }, StringSplitOptions.None)[0]; } builder.Append("<td>").Append(value.ToString()).Append("</td>"); } builder.Append("</tr>"); } builder.Append("</table></body></html>"); response.Output.Write(builder.ToString()); }
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(); } } }
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(); }
public static void DownloadFile(string filePath, HttpResponseBase response) { var fullPath = FileHelper.GetFullPath(filePath); var isExist = File.Exists(fullPath); if (isExist) { response.Clear(); response.ContentType = "application/octet-stream"; response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(Path.GetFileName(filePath), Encoding.UTF8)); // Response.AppendHeader("Content-Length", fInfo.Length.ToString()); response.WriteFile(filePath); } }
/// <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(); } }
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(); }
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(); }
private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase) { httpResponseBase.Clear(); httpResponseBase.ClearHeaders(); }
private static void SetStatusCode(HttpResponseBase response, int code) { response.Clear(); response.TrySkipIisCustomErrors = true; response.StatusCode = code; }