当前位置: 首页>>代码示例>>C#>>正文


C# HttpResponse.AddHeader方法代码示例

本文整理汇总了C#中System.Web.HttpResponse.AddHeader方法的典型用法代码示例。如果您正苦于以下问题:C# HttpResponse.AddHeader方法的具体用法?C# HttpResponse.AddHeader怎么用?C# HttpResponse.AddHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Web.HttpResponse的用法示例。


在下文中一共展示了HttpResponse.AddHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: DataTableToExcel

        /// <summary>
        /// Datatable数据填充如excel
        /// </summary>
        /// <param name="filename">excel文件名</param>
        /// <param name="dt"> 数据源</param>
        /// <param name="Response"> response响应</param>
        ///  <param name="headerStr"> 表头标题</param>
        public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr)
        {
            MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream  as用作转换,此处可以省略
            try
            {

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));
                Response.AddHeader("content-length", ms.Length.ToString());
                Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组
                Response.BinaryWrite(data);
            }
            catch
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>");
            }
            Response.Flush();
            Response.Close();
            Response.End();
            ms = null;
        }
开发者ID:mildrock,项目名称:wechat,代码行数:32,代码来源:NPOIHelper.cs

示例2: Real

        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                    case ".mp3":
                        response.ContentType = "audio/mpeg3";
                        break;
                    case ".mpeg":
                        response.ContentType = "video/mpeg";
                        break;
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".bmp":
                        response.ContentType = "image/bmp";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".doc":
                        response.ContentType = "application/msword";
                        break;
                    case ".css":
                        response.ContentType = "text/css";
                        break;
                    case ".html":
                        response.ContentType = "text/html";
                        break;
                    case ".htm":
                        response.ContentType = "text/html";
                        break;
                    case ".swf":
                        response.ContentType = "application/x-shockwave-flash";
                        break;
                    case ".exe":
                        response.ContentType = "application/octet-stream";
                        break;
                    case ".inf":
                        response.ContentType = "application/x-texinfo";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
开发者ID:Xiaoyuyexi,项目名称:LMS,代码行数:60,代码来源:HttpNotFound.cs

示例3: DownFile

 public static bool DownFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
 {
     try
     {
         FileStream input = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         BinaryReader reader = new BinaryReader(input);
         try
         {
             _Response.AddHeader("Accept-Ranges", "bytes");
             _Response.Buffer = false;
             long length = input.Length;
             long num2 = 0L;
             int count = 0x2800;
             double d = ((long) (0x3e8 * count)) / _speed;
             int millisecondsTimeout = ((int) Math.Floor(d)) + 1;
             if (_Request.Headers["Range"] != null)
             {
                 _Response.StatusCode = 0xce;
                 num2 = Convert.ToInt64(_Request.Headers["Range"].Split(new char[] { '=', '-' })[1]);
             }
             _Response.AddHeader("Content-Length", (length - num2).ToString());
             if (num2 != 0L)
             {
                 _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", num2, length - 1L, length));
             }
             _Response.AddHeader("Connection", "Keep-Alive");
             _Response.ContentType = "application/octet-stream";
             _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8));
             reader.BaseStream.Seek(num2, SeekOrigin.Begin);
             double num6 = (length - num2) / ((long) count);
             int num7 = ((int) Math.Floor(num6)) + 1;
             for (int i = 0; i < num7; i++)
             {
                 if (_Response.IsClientConnected)
                 {
                     _Response.BinaryWrite(reader.ReadBytes(count));
                     Thread.Sleep(millisecondsTimeout);
                 }
                 else
                 {
                     i = num7;
                 }
             }
         }
         catch
         {
             return false;
         }
         finally
         {
             reader.Close();
             input.Close();
         }
     }
     catch
     {
         return false;
     }
     return true;
 }
开发者ID:SoMeTech,项目名称:SoMeRegulatory,代码行数:60,代码来源:file.cs

示例4: DownloadFile

    /// <summary>
    /// Bietet die geforderte Datei zum Download an.
    /// </summary>
    /// <param name="file"></param>
    private void DownloadFile(HttpRequest request, HttpResponse response, ModuleConfig cfg, string file, bool asAttachment)
    {
      // Ermitteln des Filewappers der entsprechenden Datei.
      ConfigAgent cfgAgent = new ConfigAgent(cfg);
      FileWrapper dwnFile = cfgAgent.RootDirectory.GetFile(file);

      if (dwnFile != null)
      {
        response.CacheControl = "public";
        response.Cache.SetCacheability(HttpCacheability.Private);
        if (asAttachment)
          response.AddHeader("Content-Disposition", "attachment; filename=" + dwnFile.FileName);
        response.AddHeader("Content-Length", dwnFile.FileSize.ToString());
        String mimeType = dwnFile.MimeType;
        if (mimeType != null)
          response.ContentType = mimeType;
        response.TransmitFile(dwnFile.PhysicalPath);

        if(!Portal.API.Statistics.StatisticHelper.IsBot(request))
        {
          // In der Statistik zwischenspeichern.
          Statistic FbStatistic = new Statistic(cfgAgent.PhysicalRoot);
          FbStatistic.DownloadFile(file);
        }
      }
      else
        throw new FileNotFoundException();
    }
开发者ID:dineshkummarc,项目名称:Portal-V2.8.1,代码行数:32,代码来源:Download.cs

示例5: Real

        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                   
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".png":
                        response.ContentType = "image/png";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
开发者ID:Xiaoyuyexi,项目名称:LMS,代码行数:34,代码来源:HttpImg.cs

示例6: UpdateNoCacheForResponse

        protected void UpdateNoCacheForResponse(HttpResponse response)
        {
            response.Buffer = false;
            response.BufferOutput = false;

            response.AddHeader("Expires", "Fri, 01 Jan 1980 00:00:00 GMT");
            response.AddHeader("Pragma", "no-cache");
            response.AddHeader("Cache-Control", "no-cache, max-age=0, must-revalidate");
        }
开发者ID:dpvreony-forks,项目名称:kudu,代码行数:9,代码来源:GitServerHttpHandler.cs

示例7: BuildHeaders

 static void BuildHeaders(HttpResponse response, string mimeType, DateTime lastModified)
 {
     response.StatusCode = 200;
     response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
     response.AddHeader("content-encoding", "gzip");
     response.Cache.VaryByHeaders["Accept-encoding"] = true;
     response.AddHeader("ETag", lastModified.Ticks.ToString("x"));
     response.AddHeader("Content-Type", mimeType);
     response.AddHeader("Content-Disposition", "inline");
     response.AddHeader("Last-Modified", lastModified.ToString("R"));
 }
开发者ID:radiy,项目名称:SassAndCoffee,代码行数:11,代码来源:CompilableFileHandler.cs

示例8: ResponseFile

        public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string fullPath, long speed, string pageUrl)
        {
            FileStream myFile = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                response.AddHeader("Accept-Ranges", "bytes");
                response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                const int pack = 10240;
                int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1;
                if (request.Headers["Range"] != null)
                {
                    response.StatusCode = 206;
                    string[] range = request.Headers["Range"].Split(new[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                response.AddHeader("Connection", "Keep-Alive");
                response.ContentType = "application/octet-stream";
                response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (response.IsClientConnected)
                    {
                        response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            finally
            {
                br.Close();
                myFile.Close();
            }

            return true;
        }
开发者ID:Christind,项目名称:ucn-3semproject-dm79-group1,代码行数:52,代码来源:FileHelper.cs

示例9: SetNoCache

        /// <summary>
        /// 禁用客户端缓存
        /// </summary>
        public static void SetNoCache(HttpResponse response)
        {
            response.Buffer = true;
            response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            response.Expires = 0;
            response.CacheControl = "no-cache";
            response.AddHeader("Cache-Control", "no-cache");
            response.AddHeader("Pragma", "no-cache");

            response.Cache.SetNoStore();
            response.Cache.SetExpires(DateTime.MinValue);
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.Cache.SetValidUntilExpires(false);
        }
开发者ID:notinmood,项目名称:hiland,代码行数:17,代码来源:ResponseHelper.cs

示例10: SendPosterToBrowser

        public static void SendPosterToBrowser( PosterBuilder.Builder pb, HttpResponse resp, string posterFilename, PosterBuilder.ImgFormat.SupportedTypes outputFormat)
        {
            string filename = BuildFilename(posterFilename, outputFormat);

            resp.Clear();
            // Ensure caching is off naturally
            resp.CacheControl = "no-cache";

            resp.ContentType = PosterBuilder.ImgFormat.ToMimeType(outputFormat);
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);

            // Call our image with our amendments and have it save to the response so we can send it back
            Bitmap bmp = pb.Render();

            // Have the Poster build our new image and save the result to the outgoing response
            // ... have to do all this with MemoryStreams as PNG doesn't like being saved directly to HttpResponse.OutputStream
            // ... may as well do the same for all image types and be consistent
            using (Bitmap bitmap = pb.Render()) {

                using (MemoryStream ms = new MemoryStream()) {
                    ImageFormat outFmt = PosterBuilder.ImgFormat.ToImageFormat(outputFormat);

                    bmp.Save(ms, outFmt);

                    ms.WriteTo(resp.OutputStream);
                } // using ms

            } // using pb

            // And of course, clear up after ourselves
            pb.Dispose();
            resp.End();
        }
开发者ID:toepoke,项目名称:PosterBuilder,代码行数:33,代码来源:Helpers.cs

示例11: Read

        /// <summary>
        /// The purpose of this page is to service JSON Files. The files are already generated 
        /// elsewhere and are loaded from file system.
        /// 
        /// A query string parameter is sent to this page. Given name of 'm' and has values of '1:Get movies' file,
        /// '2:Get Movies Catalog' and so on.
        /// </summary>
        public static void Read(HttpRequest Request, HttpResponse Response)
        {
            string fileNameMovies = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies.json";
            string fileNameMoviesCatalog = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies-catalog.json";
            string fileName = "";
            string m = Request.QueryString["m"];

            if (m == null || (m != "1" && m != "2"))
            {
                Response.Write("Invalid");
                return;
            }
            switch (m)
            {
                case "1":
                    fileName = fileNameMovies;
                    break;
                case "2":
                    fileName = fileNameMoviesCatalog;
                    break;
                default:
                    break;
            }
            string s;
            using (StreamReader reader = new StreamReader(fileName))
            {
                s = reader.ReadToEnd();
            }
            Response.Write(s);
            Response.AddHeader("Access-Control-Allow-Origin", "*");
        }
开发者ID:alpermazlum,项目名称:try_git,代码行数:38,代码来源:Readson.cs

示例12: ExportToExcelFile

        /// <summary>
        /// Exporta la información a Excel.
        /// </summary>
        /// <param name="response">HttpResponse actual.</param>
        /// <param name="data">Datos a exportar.</param>
        /// <param name="nombreArchivo">Nombre del archivo Excel</param>
        public static void ExportToExcelFile(HttpResponse response, DataView data, string nombreArchivo)
        {
            var dg = new DataGrid { DataSource = data };
            dg.DataBind();

            response.Clear();
            response.Buffer = true;

            //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            response.AddHeader("Content-Disposition", "filename=" + nombreArchivo);
            response.ContentType = "application/vnd.ms-excel";
            response.Charset = "UTF-8";
            response.ContentEncoding = System.Text.Encoding.Default;

            var stringWriter = new StringWriter();
            var htmlWriter = new HtmlTextWriter(stringWriter);
            dg.RenderControl(htmlWriter);

            response.Write(stringWriter.ToString());
            //resp.Flush();
            try
            {
                response.End();
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                throw ex;
            }
        }
开发者ID:preguntoncojonero,项目名称:test,代码行数:36,代码来源:ISExcel.cs

示例13: ExportToExcel

        public void ExportToExcel(DataTable dataTable, HttpResponse response)
        {
            // Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; (i
                        <= (GridView1.Rows.Count - 1)); i++)
            {
                // Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView1.RenderControl(hw);
            // style to format numbers to string
            string style = "<style> .textmode{mso-number-format:\\@;}</style>";
            response.Write(style);
            response.Output.Write(sw.ToString());
            response.Flush();
            response.End();
        }
开发者ID:rudolfcruz,项目名称:Reports,代码行数:29,代码来源:GenReportes.cs

示例14: PrepareResponse

 public void PrepareResponse(HttpResponse httpResponse)
 {
     httpResponse.Clear();
     httpResponse.ContentType = "text/tab-separated-values";
     httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".tsv\"");
     httpResponse.BufferOutput = false;
 }
开发者ID:T-o-m-a-s-z,项目名称:MVCGrid.Net,代码行数:7,代码来源:TabDelimitedRenderingEngine.cs

示例15: Download

 void Download(HttpResponse resp, GUIDEx fileID)
 {
     lock (this)
     {
         if (resp != null)
         {
             string fullFileName = null, contentType = null;
             byte[] data = this.workDownloadService.Download(fileID, out fullFileName, out contentType);
             if (data != null && data.Length > 0)
             {
                 resp.Buffer = true;
                 resp.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fullFileName, System.Text.Encoding.UTF8));
                 resp.ContentEncoding = Encoding.GetEncoding("gb2312");//设置输出流为简体中文
                 resp.ContentType = contentType;//"application/OCTET-STREAM";
                 // resp.BufferOutput = true;
                 resp.BinaryWrite(data);
                 resp.Flush();
                 resp.End();
             }
             else
             {
                 resp.Write("文件不存在!" + fileID);
             }
         }
     }
 }
开发者ID:jeasonyoung,项目名称:csharp_sfit,代码行数:26,代码来源:AccessoriesDownload.ashx.cs


注:本文中的System.Web.HttpResponse.AddHeader方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。