/// <summary> /// 通过从 <see cref="T:System.Web.Mvc.ActionResult" /> 类继承的自定义类型,启用对操作方法结果的处理。 /// </summary> /// <param name="context">执行结果时所处的上下文。</param> /// <exception cref="System.ArgumentNullException">context</exception> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; try { if (response.StatusCode == 200) { response.ContentType = "application/json"; if (Data != null) { var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; //这里使用自定义日期格式,默认是ISO8601格式 response.Write(JsonConvert.SerializeObject(Data, timeConverter)); response.End(); } } } catch (Exception ex) { LogHelper.Log(string.Format("ExecuteResult:message:{0},StackTrace:{1}", ex.Message, ex.StackTrace)); response.Write(JsonConvert.SerializeObject(new ResultModel(ApiStatusCode.SERVICEERROR))); response.End(); } }
/* 微信授权后跳转到的页面中通过code获取用户信息 */ public void SecondPage_RedirectUrl_GetUserInfoByCode(HttpSessionStateBase session, HttpResponseBase response, string code) { string url = @"https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=" + _app_id + "&secret=" + _app_secret + "&code=" + code + "&grant_type=authorization_code"; try { if (string.IsNullOrEmpty(code)) { throw new Exception("code为空"); } var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage res = httpClient.GetAsync(url).Result; //string statusCode = response.StatusCode.ToString(); if (res.IsSuccessStatusCode) { string result = res.Content.ReadAsStringAsync().Result; JObject o = JObject.Parse(result); JToken jt_errcode; if (o.TryGetValue("errcode", out jt_errcode)) { throw new Exception("微信服务器返回错误:【" + o["errcode"].ToString() + "】" + o["errmsg"].ToString()); } else { WxWebApiRetAccessToken at = new WxWebApiRetAccessToken(); at.access_token = o["access_token"].ToString(); at.expires_in = int.Parse(o["expires_in"].ToString()); at.refresh_token = o["refresh_token"].ToString(); at.openid = o["openid"].ToString(); at.scope = o["scope"].ToString(); for (int i = 0; i < session.Keys.Count; ++i) { if (session.Keys[i] == _session_key_for_openid) { session.Remove(_session_key_for_openid); break; } } session.Add(_session_key_for_openid, at.openid); response.Redirect(_root_url); response.End(); } } else { throw new Exception("服务器返回:" + res.StatusCode.ToString()); } } catch (System.Exception ex) { response.Redirect(_error_url + "?error=" + HttpUtility.UrlEncode(ex.Message)); response.End(); } }
public ActionResult Forbidden() { Response.StatusCode = 403; Response.StatusDescription = "Authorization failed"; Response.Flush(); Response.End(); return(null); }
private static void DownloadPdf(HttpResponseBase Response, MemoryStream mstream) { mstream.WriteTo(Response.OutputStream); Response.ClearContent(); Response.Clear(); Response.End(); }
public void ToExcel_XLSX(HttpResponseBase Response, System.Data.DataTable clientsList, string nome_relatorio) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Lotes"); workSheet.Cells[1, 1].LoadFromDataTable(clientsList, true); workSheet.Cells.AutoFitColumns(); var cab = workSheet.Row(1); cab.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; cab.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue); using (var memoryStream = new MemoryStream()) { Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + nome_relatorio + ".xlsx"); excel.SaveAs(memoryStream); memoryStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); } }
public void End() { if (_context != null) { _context.End(); } }
protected override void WriteFile(HttpResponseBase response) { var type = ViewModelDescriptor.GetTypeDescriptor(_itemType); Grid grid = new Grid(); var user = _securityHelper.GetCurrentUser(); var properties = type.Properties.Where(x => x.Show && (user == null || x.Permission.Check(user.CurrentUser))).OrderBy(x => x.Order).ToList(); foreach (var propertyDescriptor in properties) { grid.Columns.Add(new GridColumn(propertyDescriptor.ShortName, 80)); } foreach (var item in _items) { var row = grid.NewRow(); for (int i = 0; i < properties.Count; i++) { var propertyDescriptor = properties[i]; row[i].Text = string.Format(propertyDescriptor.ShortNameFormat, propertyDescriptor.GetValue(item)); } grid.Rows.Add(row); } ExcelExport export = new ExcelExport(); var bytes = export.Export(grid); response.BinaryWrite(bytes); response.End(); }
public static void RedirectPermanent(this HttpResponseBase response, string url) { response.StatusCode = 301; response.StatusDescription = "301 Moved Permanently"; response.RedirectLocation = url; response.End(); }
/// <summary> /// Redirects to the specified URL. /// </summary> /// <param name="response">The response to use for redirection.</param> /// <param name="url">The URL to redirect to.</param> /// <param name="bypassSecurityWarning">If set to <c>true</c> security warnings will be bypassed.</param> public void Redirect(HttpResponseBase response, string url, bool bypassSecurityWarning) { if (bypassSecurityWarning) { Logger.Log("Bypassing security warning via a response header and JavaScript."); url = JsEncodeUrl(url); // Clear the current response buffer. response.Clear(); // Add a refresh header to the response for the new path. response.AddHeader("Refresh", "0;URL=" + url); // Also, add JavaScript to replace the current location as backup. response.Write("<html><head><title></title>"); response.Write("<script language=\"javascript\">window.location = '"); response.Write(url); response.Write("';</script>"); response.Write("</head><body></body></html>"); } else { Logger.Log("Issuing permanent redirect."); // Permanent redirect. // TODO: Make the status code configurable (i.e. permanent vs. temporary). response.StatusCode = 301; response.RedirectLocation = url; } // End the current response. response.End(); }
public static void KreirajPdf(string html, HttpResponseBase response) { try { //MemoryStream ms = new MemoryStream(); TextReader reader = new StringReader(html); Document document = new Document(PageSize.A4, 30, 30, 30, 30); HTMLWorker worker = new HTMLWorker(document); PdfWriter writer = PdfWriter.GetInstance(document, response.OutputStream); document.Open(); worker.Parse(reader); document.Close(); response.ContentType = "application/pdf"; response.Cache.SetCacheability(HttpCacheability.NoCache); response.Write(document); response.AddHeader("Content-Disposition", "attachment;filename=\"Report" + DateTime.Now.Ticks + ".pdf\""); response.End(); } catch (Exception ex) { LoggingHelper.Greska(ex, nameof(Helpers), nameof(KreirajPdf)); } }
// public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; response.ContentType = (saveAsXML) ? "text/xml" : "application/vnd.ms-excel"; response.AddHeader("content-disposition", "attachment; filename=" + fileName); byte[] buffer = new byte[4096]; while (true) { int read = this.excelStream.Read(buffer, 0, buffer.Length); if (read == 0) { break; } response.OutputStream.Write(buffer, 0, read); } response.End(); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpResponseBase response = filterContext.HttpContext.Response; HttpRequestBase request = filterContext.HttpContext.Request; if (filterContext.HttpContext.User.Identity.IsAuthenticated) { //已经登录代码 } else { if (!request.IsAjaxRequest()) { string str = request.Url.AbsoluteUri.ToLower(); string str2 = "/login"; filterContext.Result = new RedirectResult(string.Format("{0}?returnUrl={1}", str2, str)); } else { response.SetStatus(401); } filterContext.Result = new HttpUnauthorizedResult(); //这一行保证不再执行Action的代码 response.End(); //必须加上这句,否则返回前台status始终是200 return; } }
protected override void WriteFile(HttpResponseBase response) { Grid grid = new Grid(); var properties = _table.Columns; foreach (DataColumn propertyDescriptor in properties) { grid.Columns.Add(new GridColumn(propertyDescriptor.Caption, 80)); } foreach (DataRow item in _table.Rows) { var row = grid.NewRow(); for (int i = 0; i < properties.Count; i++) { var propertyDescriptor = properties[i]; row[i].Text = item[i]; } grid.Rows.Add(row); } ExcelExport export = new ExcelExport(); var bytes = export.Export(grid); response.BinaryWrite(bytes); response.End(); }
public static void ToExcel(HttpResponseBase response, IEnumerable <IExportDataSource> data, string fileName) { var workBook = new XLWorkbook(); foreach (var item in data) { var workSheet = workBook.Worksheets.Add(item.Table); workSheet.ConditionalFormats.RemoveAll(); workSheet.Table("Table1").Theme = XLTableTheme.None; workSheet.Table("Table1").ShowRowStripes = false; if (item.Action != null) { item.Action(workSheet); } } response.Clear(); response.Buffer = true; response.Charset = ""; response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xlsx", fileName)); using (var MyMemoryStream = new MemoryStream()) { workBook.SaveAs(MyMemoryStream); MyMemoryStream.WriteTo(response.OutputStream); response.Flush(); response.End(); } }
public static void ToExcel(HttpResponseBase response, object clientsList, string fileName, GridOnRowCreated onRowCreated = null) { var grid = new GridView(); if (onRowCreated != null) { grid.RowCreated += new GridViewRowEventHandler(onRowCreated); } grid.DataSource = clientsList; grid.DataBind(); response.ClearContent(); fileName = String.Format("{0}.xls", fileName); response.AddHeader("content-disposition", "attachment; filename=" + fileName); response.ContentType = "application/excel"; using (var sw = new StringWriter()) { using (var htw = new HtmlTextWriter(sw)) { grid.RenderControl(htw); response.Write(sw.ToString()); response.End(); } } }
public override TaskContinuation Execute() { const string Prefix = "http://www."; string url = httpContext.Request.Url.ToString(); bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); bool shouldContinue = true; if (startsWith3W) { string newUrl = "http://" + url.Substring(Prefix.Length); HttpResponseBase response = httpContext.Response; response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.Status = "301 Moved Permanently"; response.RedirectLocation = newUrl; response.SuppressContent = true; response.End(); shouldContinue = false; } return(shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break); }
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=Export.xls"); //Response.ContentType = "application/excel"; //Response.AddHeader("content-disposition", "attachment;filename=Lotes.xls"); //Response.AddHeader("Content-Type", "application/vnd.ms-excel"); //Response.AddHeader("content-disposition", "attachment; filename= LotesExcel.xlsx"); //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename= LotesTestes.xlsx"); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); }
public void Export(IEnumerable dataForList, HttpResponseBase responce) { ExcelPackage excel = new ExcelPackage(); var workSheet = excel.Workbook.Worksheets.Add("Sheet1"); List <Comment> comments = dataForList as List <Comment>; if (comments != null) { workSheet.Cells[1, 1].LoadFromCollection(comments, true); } List <Post> posts = dataForList as List <Post>; if (posts != null) { workSheet.Cells[1, 1].LoadFromCollection(posts, true); } using (var memoryStream = new MemoryStream()) { responce.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; responce.AddHeader("content-disposition", "attachment; filename=Contact.xlsx"); excel.SaveAs(memoryStream); memoryStream.WriteTo(responce.OutputStream); responce.Flush(); responce.End(); } }
public FileStreamResult ExportWord(string htmlString, string fileName) { //确保加上后缀名 if (fileName.IndexOf(".doc", StringComparison.OrdinalIgnoreCase) < 0) { fileName = fileName + ".doc"; } HttpResponseBase response = ControllerContext.HttpContext.Response; response.Charset = "GB2312"; response.ContentEncoding = Encoding.GetEncoding("GB2312"); response.ContentType = "application/ms-word"; response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName)); StringWriter writer = new StringWriter(); HtmlTextWriter writer2 = new HtmlTextWriter(writer); writer2.WriteFullBeginTag("html"); writer2.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=GB2312\">"); writer2.WriteLine(htmlString); writer2.WriteEndTag("html"); response.Write(writer.ToString()); response.Flush(); response.End(); return(new FileStreamResult(Response.OutputStream, "application/ms-word")); }
public virtual void Execute(HttpResponseBase response) { response.StatusCode = 200; response.ContentType = "text/html"; var masterControls = new List <IControlPanelControl>(); masterControls.AddRange(CreateHeaderControls(_securityState)); masterControls.AddRange(_controls); masterControls.AddRange(CreateFooterControls()); using (var writer = new HtmlTextWriter(response.Output)) { // this securitydisabler allows the control panel to execute unfettered when debug compilation is enabled but you are not signed into Sitecore using (new SecurityDisabler()) { foreach (var control in masterControls) { control.Render(writer); } } } response.End(); }
public void Apply(HttpResponseBase response) { if (response == null) { throw new ArgumentNullException("response"); } response.Cache.SetCacheability(Cacheability); if (HttpStatusCode == HttpStatusCode.SeeOther || Location != null) { if (Location == null) { throw new InvalidOperationException("Missing Location on redirect."); } if (HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException("Invalid HttpStatusCode for redirect, but Location is specified"); } response.Redirect(Location.ToString()); } else { response.StatusCode = (int)HttpStatusCode; response.ContentType = ContentType; response.Write(Content); response.End(); } }
public static void Generar(LocalReport localReport, string filename, FormatoReporte formato, HttpResponseBase response) { string reportType = formato == FormatoReporte.PDF ? "PDF" : formato == FormatoReporte.EXCEL ? "EXCEL" : "WORD"; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + reportType + "</OutputFormat>" + //" <OutputFormat>PDF</OutputFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; localReport.EnableHyperlinks = true; renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); response.Clear(); response.ContentType = mimeType; response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + fileNameExtension); response.BinaryWrite(renderedBytes); response.End(); }
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("该方法当前不允许使用Get"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding != null) { response.ContentEncoding = this.ContentEncoding; } if (this.Data != null) { string strJson = JsonConvert.SerializeObject(this.Data, JsonSerializerSettings); response.Write(strJson); response.End(); } }
public static void ExportData(object data, HttpResponseBase Response, string fileName) { //List<object> pdoList = repoDemand.GetListByYearWeek(yearWeek, productionType).ToList(); var gv = new GridView(); gv.DataSource = data;// pdoList; gv.DataBind(); Response.ClearContent(); Response.Buffer = true; //Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250"); Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //Response.Write("ąęćżźń󳥌ŻŹĆŃŁÓĘ"); Response.Write('\uFEFF'); Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName)); Response.ContentType = "application/ms-excel"; //Response.Charset = ""; //Response.ContentType = "text/rtf; charset=UTF-8"; StringWriter objStringWriter = new StringWriter(); HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter); gv.RenderControl(objHtmlTextWriter); Response.Output.Write(objStringWriter.ToString()); Response.Flush(); Response.End(); }
public static void ExportPDF(DataTable dt, HttpResponseBase Response) { using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { GridView b = new GridView(); b.DataSource = dt; b.DataBind(); b.RenderControl(hw); //string mystring = DataTableToCollection.ConvertDataTableToHTMLString(dt,"","","","",true,true); StringReader sr = new StringReader(hw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Records.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Write(pdfDoc); Response.End(); } } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { response.Write(Serialization.JSONEncode(Data)); } response.End(); }
public static void Apply(this CommandResult commandResult, HttpResponseBase response) { if (commandResult == null) { throw new ArgumentNullException(nameof(commandResult)); } if (response == null) { throw new ArgumentNullException(nameof(response)); } if (commandResult.HttpStatusCode == HttpStatusCode.SeeOther || commandResult.Location != null) { if (commandResult.Location == null) { throw new InvalidOperationException("Missing Location on redirect."); } if (commandResult.HttpStatusCode != HttpStatusCode.SeeOther) { throw new InvalidOperationException("Invalid HttpStatusCode for redirect, but Location is specified"); } response.Redirect(commandResult.Location.OriginalString); } else { response.StatusCode = (int)commandResult.HttpStatusCode; response.ContentType = commandResult.ContentType; response.Write(commandResult.Content); response.End(); } }
public static void RedirectPermanent(this HttpResponseBase response, string url) { response.Clear(); response.Status = "301 Moved Permanently"; response.AddHeader("Location", url); response.End(); }
/// <summary> /// 重写ExecuteResult /// </summary> /// <param name="context">ControllerContext</param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(this.ContentType)) { response.ContentType = this.ContentType; } else { response.ContentType = "application/json"; } if (this.ContentEncoding == null) { this.ContentEncoding = Encoding.UTF8; } response.ContentEncoding = this.ContentEncoding; if (this.Data != null) { var data = NewtonsoftSerialize(this.Data); byte[] bytes = this.ContentEncoding.GetBytes(data); response.BufferOutput = true; response.AddHeader("Content-Length", bytes.Length.ToString()); response.BinaryWrite(bytes); response.Flush(); response.End(); } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } // get rendered HTML from view string html = ViewRenderer.RenderViewToString(context, ViewName, Model); var cssFiles = CssHelper.GetAllCssPaths(html); //html = ClearHtmlStrategy.Clear(html); // generate the PDF content from HTML var pageConfig = PageConfig != null ? PageConfig : PageSize.A4; byte[] content = HtmlToPdfRenderer.Render(html, cssFiles, pageConfig); var contentDisposition = IsAttachment ? "attachement" : "inline"; HttpResponseBase response = context.HttpContext.Response; response.Clear(); response.ClearContent(); response.ClearHeaders(); response.ContentType = "application/pdf"; response.AppendHeader("Content-Disposition", $"{contentDisposition};filename={Filename}.pdf"); response.AddHeader("Content-Length", content.Length.ToString()); response.BinaryWrite(content); response.OutputStream.Flush(); response.OutputStream.Close(); response.End(); }