上传zip

1、ZipCompressionUtil

using HRS.Lib.Comm.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HRS.Lib.Comm.Compress
{
    public class ZipCompressionUtil
    {
        public static void ZipFile(string FileToZip, string ZipedFile, string pwd, int CompressionLevel, int BlockSize)
        {
            //Get all DirectoryInfo
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
            }

            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipStream.Password = pwd;
            ZipEntry ZipEntry = new ZipEntry("ZippedFile");
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[BlockSize];
            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
            ZipStream.Write(buffer, 0, size);
            try
            {
                while (size < StreamToZip.Length)
                {
                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                    ZipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            ZipStream.Finish();
            ZipStream.Close();
            StreamToZip.Close();
        }

        //Get all DirectoryInfo
        private static void Direct(DirectoryInfo di, ref ZipOutputStream s, Crc32 crc)
        {
            //DirectoryInfo di = new DirectoryInfo(filenames);
            DirectoryInfo[] dirs = di.GetDirectories("*");

            //±éÀúĿ¼ÏÂÃæµÄËùÓеÄ×ÓĿ¼
            foreach (DirectoryInfo dirNext in dirs)
            {
                //½«¸ÃĿ¼ÏµÄËùÓÐÎļþÌí¼Óµ½ ZipOutputStream s ѹËõÁ÷ÀïÃæ
                FileInfo[] a = dirNext.GetFiles();
                WriteStream(ref s, a, crc);

                //µÝ¹éµ÷ÓÃÖ±µ½°ÑËùÓеÄĿ¼±éÀúÍê³É
                Direct(dirNext, ref s, crc);
            }
        }

        private static int bufferSize = 2048;
        private static void WriteStream(ref ZipOutputStream s, FileInfo[] a, Crc32 crc)
        {
            foreach (FileInfo fi in a)
            {
                //string fifn = fi.FullName;
                FileStream fs = fi.OpenRead();

                try
                {
                    //ZipEntry entry = new ZipEntry(file);    Path.GetFileName(file)
                    //string file = fi.FullName;
                    //file = file.Replace(cutStr, "");

                    ZipEntry entry = new ZipEntry(Path.GetFileName(fi.FullName));

                    entry.DateTime = DateTime.Now;

                    // set Size and the crc, because the information
                    // about the size and crc should be stored in the header
                    // if it is not set it is automatically written in the footer.
                    // (in this case size == crc == -1 in the header)
                    // Some ZIP programs have problems with zip files that don't store
                    // the size and crc in the header.
                    entry.Size = fs.Length;

                    // ²ÉÓ÷ֿéдÈë±ÜÃâÄÚ´æÏûºÄ¹ý´óµÄÎÊÌ⣬Òò´ËÎÞ·¨ÔÚ¿ªÊ¼¾Í¼ÆËãcrc
                    //crc.Reset();
                    //crc.Update(buffer);
                    //entry.Crc = crc.Value;

                    s.PutNextEntry(entry);

                    byte[] buffer = new byte[bufferSize];
                    int readSize = 0;
                    while ((readSize = fs.Read(buffer, 0, buffer.Length)) > 0)
                        s.Write(buffer, 0, readSize);
                    fs.Close();
                }
                catch (Exception)
                {
                    fs.Close();
                    throw;
                }
            }
        }

        /// <summary>
        /// ѹËõÖ¸¶¨Ä¿Â¼ÏÂÖ¸¶¨Îļþ(°üÀ¨×ÓĿ¼ÏµÄÎļþ)
        /// </summary>
        /// <param name="zippath">args[0]ΪÄãҪѹËõµÄĿ¼ËùÔڵķ¾¶ 
        /// ÀýÈ磺D:\\temp\\   (×¢Òâtemp ºóÃæ¼Ó \\ µ«ÊÇÄãд³ÌÐòµÄʱºòÔõôÐ޸Ķ¼¿ÉÒÔ)</param>
        /// <param name="zipfilename">args[1]ΪѹËõºóµÄÎļþÃû¼°Æä·¾¶
        /// ÀýÈ磺D:\\temp.zip</param>
        /// <param name="fileFilter">Îļþ¹ýÂË, ÀýÈç*.xml,ÕâÑùֻѹËõ.xmlÎļþ.</param>
        ///
        public static bool ZipFileMain(string zippath, string zipfilename, string fileFilter, string pwd)
        {
            ZipOutputStream s = null;
            try
            {
                //string filenames = Directory.GetFiles(args[0]);

                Crc32 crc = new Crc32();
                s = new ZipOutputStream(File.Create(zipfilename));
                s.Password = pwd;
                s.SetLevel(6); // 0 - store only to 9 - means best compression

                DirectoryInfo di = new DirectoryInfo(zippath);

                FileInfo[] a = di.GetFiles(fileFilter);

                //ѹËõÕâ¸öĿ¼ÏµÄËùÓÐÎļþ
                WriteStream(ref s, a, crc);
                //ѹËõÕâ¸öĿ¼ÏÂ×ÓĿ¼¼°ÆäÎļþ
                Direct(di, ref s, crc);

                s.Finish();
                s.Close();
            }
            catch
            {
                if (s != null)
                    s.Close();
                throw;
            }
            return true;
        }

        /// <summary>
        /// ½âѹËõÎļþ(ѹËõÎļþÖк¬ÓÐ×ÓĿ¼)
        /// </summary>
        /// <param name="zipfilepath">´ý½âѹËõµÄÎļþ·¾¶</param>
        /// <param name="unzippath">½âѹËõµ½Ö¸¶¨Ä¿Â¼</param>
        public static void UnZip(string zipfilepath, string unzippath)
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //Éú³É½âѹĿ¼
                    DirectoryUtil.CreateOpenDir(unzippath);
                    string filePath = Path.Combine(unzippath, Path.GetFileName(theEntry.Name));
                    if (filePath != string.Empty)
                    {
                        //Èç¹ûÎļþµÄѹËõºó´óСΪ0ÄÇô˵Ã÷Õâ¸öÎļþÊÇ¿ÕµÄ,Òò´Ë²»ÐèÒª½øÐжÁ³öдÈë
                        if (theEntry.CompressedSize == 0)
                            break;

                        using (FileStream streamWriter = File.Create(filePath))
                        {
                            int size = 64 * 1024;
                            byte[] data = new byte[size];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            streamWriter.Close();
                        }
                    }
                }
                s.Close();
            }
        }
        public static void UnZipContainFolder(string zipfilepath, string unzippath)
        {
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    //Éú³É½âѹĿ¼
                    DirectoryUtil.CreateOpenDir(unzippath);
                    string path = unzippath + @"\" + theEntry.Name;                    
                    if (theEntry.IsDirectory)
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                    }
                    else
                    {
                        var dir = Path.GetDirectoryName(path);
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }
                        if (path != string.Empty)
                        {
                            //Èç¹ûÎļþµÄѹËõºó´óСΪ0ÄÇô˵Ã÷Õâ¸öÎļþÊÇ¿ÕµÄ,Òò´Ë²»ÐèÒª½øÐжÁ³öдÈë
                            if (theEntry.CompressedSize == 0)
                                break;

                            using (FileStream streamWriter = File.Create(path))
                            {
                                int size = 64 * 1024;
                                byte[] data = new byte[size];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                }
                s.Close();
            }
        }
    }
}
View Code

2、UploadZip

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace HRS.AdminWeb.Helper
{
    /// <summary>
    /// 上传zip
    /// </summary>
    public class UploadZip
    {
        public string GetUniqueString()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 上传压缩文件
        /// </summary>
        /// <param name="hifile"></param>
        /// <param name="strAbsolutePath"></param>
        /// <returns></returns>
        public string SaveFile(HttpPostedFileBase hifile, string strAbsolutePath)
        {
            string strOldFilePath = "";
            string strExtension = "";
            string strNewFileName = "";
            string strNewMid = "";
            string strFullPath = "";

            if (hifile.FileName != string.Empty)
            {
                strOldFilePath = hifile.FileName;
                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));
                strNewMid = GetUniqueString();
                strNewFileName = strNewMid + strExtension;
                strFullPath = Utils.GetFolderPath(strAbsolutePath, false);
                if (!Directory.Exists(Path.GetDirectoryName(strFullPath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(strFullPath));
                }
                hifile.SaveAs(strFullPath + strNewFileName);
                HRS.Lib.Comm.Compress.ZipCompressionUtil.UnZip(strFullPath + strNewFileName, strFullPath + strNewMid);
            }
            return strNewMid;
        }
    }
}
View Code

3、controller

using HRS.AdminWeb.Helper;
using HRS.AdminWeb.JsonCommunication;
using HRS.AdminWeb.WcfClient;
using HRS.Lib.Comm;
using HRS.Lib.Comm.IO.FileServer;
using HRS.Service.Contract.ContractParam.Base;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace HRS.AdminWeb.Controllers
{
    public class FileController : BaseController
    {
        //
        // GET: /File/
        public ActionResult Download(string fid, string fileName)
        {
            try
            {

                var fi = FileManager.GetFileInfo(Uri.EscapeDataString(fid));
                if (null != fi)
                {
                    string contentType = MimeMapping.GetMimeMapping(fi.Name);

                    return File(fi.FullPath, contentType, fi.Name);
                }
                else
                {
                    if (string.IsNullOrEmpty(fileName))
                    {
                        return File(Path.Combine(FileManager.BasePath, fid), MimeMapping.GetMimeMapping(fid), fid.Substring(fid.LastIndexOf(@"\") + 1));
                    }
                    else
                    {
                        return File(Path.Combine(FileManager.BasePath, fid), MimeMapping.GetMimeMapping(fid), Uri.EscapeDataString(fileName));
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
              //  return Redirect("~/File/GetBatchUploadFileRecord");
            }
        }


        public ActionResult Upload()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string key in Request.Files.Keys)
            {
                var fileInfos = FileManager.WriteFile(Request.Files[key]);
                if (null == fileInfos)
                {
                    throw new Exception("文件保存失败");
                }
                dic.Add(key, fileInfos.FID);
                dic.Add("fileName", fileInfos.Name);
            }

            return Json(dic);
        }

        /// <summary>
        /// 百度富文本使用
        /// </summary>
        /// <param name="fidPre"></param>
        /// <returns></returns>
        public ActionResult UploadForKindEditor(string fidPre = "")
        {
            JsonForKindEditor jscon = new JsonForKindEditor();
            if (Request.Files.Keys.Count > 0)
            {
                var fileInfos = FileManager.WriteFile(Request.Files[0]);
                if (null == fileInfos)
                {
                    throw new Exception("文件保存失败");
                }
                //重新复制上传文件到指定文件夹
                if (string.IsNullOrEmpty(fidPre))
                {
                    fidPre = "QA";
                }
                BaseReqParam param = new BaseReqParam();
                param.ExtraData["FidPre"] = fidPre;
                param.ExtraData["FID"] = fileInfos.FID;
                param.ExtraData["FileName"] = fileInfos.Name;

                var resp = ServiceCommunicator.AnonymousExecuteOperation<BaseResponse>("QA.UploadForKindEditor", param);
                jscon.url = "/file/download?fid=" + resp.ExtraData.GetStr("FilePath");
                jscon.error = 0;
            }
            return Json(jscon);
        }

        public ActionResult GetFiles(BaseRequstJson requestJson)
        {
            return CatchErr(() =>
            {
                if (Session["UserID"] == null) throw new Exception("NotLogin");
                //获得param数据
                var param = GetParam(requestJson.ParamTypeName, requestJson.ParamJsonData);
                //与wcf服务通讯
                var resp =
                    ServiceCommunicator.ExecuteOperation<object>(requestJson.MethodFullName, param);
                if (null != resp && resp is BaseResponse)
                {
                    var response = resp as BaseResponse;
                    if (response.ExtraData.ContainsKey("Uri"))
                    {
                        response.ExtraData["Uri"] = response.ExtraData["Uri"].ToString();
                        return Json(new BaseReponseJson() { Success = true, ResponseData = response });

                        //using (var fileMgt = FileSerMgt.GetFileSerMgt("UserTempDir"))
                        //{
                        //response.ExtraData["Uri"] =
                        //fileMgt.GetFullWebStaticPath(response.ExtraData["Uri"].ToString());
                        //return Json(new BaseReponseJson() { Success = true, ResponseData = response });
                        /*
                        var filePath = response.ExtraData["Uri"].ToString();

                        var fileInfo = new FileInfo(filePath);
                        Response.Clear();
                        Response.ClearContent();
                        Response.ClearHeaders();
                        Response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(response.ExtraData["Uri"].ToString()));
                        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                        Response.AddHeader("Content-Transfer-Encoding", "binary");
                        Response.ContentType = "application/octet-stream";
                        Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                        Response.WriteFile(fileInfo.FullName);
                        Response.Flush();
                        Response.End();
                         */
                        //}
                    }
                }
                return Json(new BaseReponseJson() { Success = true, ResponseData = resp });
            });
        }


        public ActionResult GetBatchUploadFileRecord()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult UploadFileToFileServer()
        {
            try
            {
                var fileServerUri = ConfigurationManager.AppSettings["FileServerUri"];

                string tempUrl = fileServerUri + "?" + Request.QueryString.ToString();

                //创建 Http 请求 用于将 替换后 请求报文 发往 目标 Url

                var broker = new MyProxy.RequestBroker();
                var resp = broker.BrokerAsync(Request, tempUrl);

                var hash = new System.Collections.Hashtable();
                using (var stream = resp.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var str = reader.ReadToEnd();
                        return Content(str);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = 1, message = ex.Message });
            }
        }


        [HttpPost]
        public ContentResult UploadImagePdf(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                UploadImage ui = new UploadImage();
                var strExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
                if (!strExtension.Equals(".pdf", StringComparison.OrdinalIgnoreCase) && !ui.IsAllowedExtension(file))
                {
                    return Content(JsonConvert.SerializeObject(new { status = false, message = "错误的文件类型" }));
                }
                //if (!ui.IsAllowedLength(file))
                //{
                //    return Content(JsonConvert.SerializeObject(new { status = false, message = "图片大小必须大于1000*480" }));
                //}
                string path = System.Configuration.ConfigurationManager.AppSettings["UploadImageUrl"];
                try
                {
                    var fileName = ui.SaveFile(file, Server.MapPath(path));
                    return Content(JsonConvert.SerializeObject(new
                    {
                        status = true,
                        fileName = fileName,
                        url = Path.Combine(path + fileName)
                    }));
                }
                catch
                {
                    return Content(JsonConvert.SerializeObject(new { status = false, message = "上传出错,请重试" }));
                }
            }
            else
            {
                return Content(JsonConvert.SerializeObject(new { status = false, msg = "请上传文件!" }));
            }
        }

        [HttpPost]
        public ContentResult UploadZip(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                if (file.ContentLength > 1024 * 1024 * 10)
                {
                    return Content(JsonConvert.SerializeObject(new { status = false, message = "文件大小不能超过10M" }));
                }
                var ui = new UploadZip();
                var strExtension = file.FileName.Substring(file.FileName.LastIndexOf("."));
                if (!strExtension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    return Content(JsonConvert.SerializeObject(new { status = false, message = "错误的文件类型" }));
                }
                string path = System.Configuration.ConfigurationManager.AppSettings["UploadImageUrl"];
                try
                {
                    var fileName = ui.SaveFile(file, Server.MapPath(path + "\\InvoiceBatch"));
                    return Content(JsonConvert.SerializeObject(new
                    {
                        status = true,
                        fileName = fileName
                    }));
                }
                catch
                {
                    return Content(JsonConvert.SerializeObject(new { status = false, message = "上传出错,请重试" }));
                }
            }
            else
            {
                return Content(JsonConvert.SerializeObject(new { status = false, msg = "请上传文件!" }));
            }
        }

        [HttpPost]
        public ActionResult DeleteImage(string fileName)
        {
            UploadImage ui = new UploadImage();
            string path = System.Configuration.ConfigurationManager.AppSettings["UploadImageUrl"];
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    return Json(new { status = false, message = "删除出错,文件名称为空" });
                }
                ui.DeleteFile(Server.MapPath(path), fileName);
                return Json(new { status = true });
            }
            catch
            {
                return Json(new { status = false, message = "删除出错,请重试" });
            }
        }

        /// <summary>
        /// 设置请求头
        /// </summary>
        /// <param name="nrq"></param>
        /// <param name="orq"></param>
        private void SetRequestHead(WebRequest nrq, HttpRequestBase orq)
        {
            foreach (var key in orq.Headers.AllKeys)
            {
                try
                {
                    nrq.Headers.Add(key, orq.Headers[key]);
                }
                catch (Exception)
                {

                    continue;
                }

            }
        }


        /// <summary>
        /// 设置请求 报文体
        /// </summary>
        /// <param name="nrq"></param>
        /// <param name="orq"></param>
        private void SetRequestBody(WebRequest nrq, HttpRequestBase orq)
        {
            nrq.Method = "POST";
            var nStream = nrq.GetRequestStream();
            byte[] buffer = new byte[1024 * 2];
            int rLength = 0;
            do
            {
                rLength = orq.InputStream.Read(buffer, 0, buffer.Length);
                nStream.Write(buffer, 0, rLength);
            } while (rLength > 0);
        }

        /// <summary>
        /// 设置响应头
        /// </summary>
        /// <param name="nrp"></param>
        /// <param name="orp"></param>
        private void SetResponeHead(WebResponse nrp, HttpResponseBase orp)
        {
            foreach (var key in nrp.Headers.AllKeys)
            {
                try
                {
                    orp.Headers.Add(key, nrp.Headers[key]);
                }
                catch (Exception)
                {

                    continue;
                }

            }
        }

        /// <summary>
        /// 设置响应报文体
        /// </summary>
        /// <param name="nrp"></param>
        /// <param name="orp"></param>
        private void SetResponeBody(WebResponse nrp, HttpResponseBase orp)
        {
            var nStream = nrp.GetResponseStream();
            byte[] buffer = new byte[1024 * 2];
            int rLength = 0;
            do
            {
                rLength = nStream.Read(buffer, 0, buffer.Length);
                orp.OutputStream.Write(buffer, 0, rLength);
            } while (rLength > 0);
        }

    }
    public class JsonForKindEditor
    {
        public int error { get; set; }
        public string url { get; set; }
    }
}


namespace MyProxy
{
    /// <summary>
    /// Asynchronous operation to proxy or "broker" a request via MVC
    /// </summary>
    internal class RequestBroker
    {
        /*
         * HttpWebRequest is a little protective, and if we do a straight copy of header information we will get ArgumentException for a set of 'restricted' 
         * headers which either can't be set or need to be set on other interfaces. This is a complete list of restricted headers.
         */
        private static readonly string[] RestrictedHeaders = new string[] { "Accept", "Connection", "Content-Length", "Content-Type", "Date", "Expect", "Host", "If-Modified-Since", "Range", "Referer", "Transfer-Encoding", "User-Agent", "Proxy-Connection" };


        public HttpWebResponse BrokerAsync(HttpRequestBase requestToBroker, string redirectToUrl)
        {
            var httpRequest = BuildWebRequest(requestToBroker, redirectToUrl);

            return this.DoBroker(httpRequest);
        }

        private HttpWebResponse DoBroker(HttpWebRequest requestToBroker)
        {
            var startTime = DateTime.UtcNow;

            HttpWebResponse response;
            try
            {
                response = requestToBroker.GetResponse() as HttpWebResponse;
            }
            catch (WebException e)
            {
                Trace.TraceError("Broker Fail: " + e.ToString());

                response = e.Response as HttpWebResponse;
            }

            return response;
        }

        public static void BuildControllerResponse(HttpResponseBase httpResponseBase, HttpWebResponse brokeredResponse)
        {
            httpResponseBase.Charset = brokeredResponse.CharacterSet;
            httpResponseBase.ContentType = brokeredResponse.ContentType;

            foreach (Cookie cookie in brokeredResponse.Cookies)
            {
                httpResponseBase.Cookies.Add(CookieToHttpCookie(cookie));
            }

            foreach (var header in brokeredResponse.Headers.AllKeys
                .Where(k => !k.Equals("Transfer-Encoding", StringComparison.InvariantCultureIgnoreCase)))
            {
                httpResponseBase.Headers.Add(header, brokeredResponse.Headers[header]);
            }

            httpResponseBase.StatusCode = (int)brokeredResponse.StatusCode;
            httpResponseBase.StatusDescription = brokeredResponse.StatusDescription;

            BridgeAndCloseStreams(brokeredResponse.GetResponseStream(), httpResponseBase.OutputStream);
        }

        private static HttpWebRequest BuildWebRequest(HttpRequestBase requestToBroker, string redirectToUrl)
        {
            var httpRequest = (HttpWebRequest)WebRequest.Create(redirectToUrl);

            if (requestToBroker.Headers != null)
            {
                foreach (var header in requestToBroker.Headers.AllKeys)
                {
                    if (RestrictedHeaders.Any(h => header.Equals(h, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        continue;
                    }

                    httpRequest.Headers.Add(header, requestToBroker.Headers[header]);
                }
            }

            httpRequest.Accept = string.Join(",", requestToBroker.AcceptTypes);
            httpRequest.ContentType = requestToBroker.ContentType;
            httpRequest.Method = requestToBroker.HttpMethod;

            if (requestToBroker.UrlReferrer != null)
            {
                httpRequest.Referer = requestToBroker.UrlReferrer.AbsoluteUri;
            }

            httpRequest.UserAgent = requestToBroker.UserAgent;

            /* This is a performance change which I like.
             * If this is not explicitly set to null, the CLR will do a registry hit for each request to use the default proxy.
             */
            httpRequest.Proxy = null;

            if (requestToBroker.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
            {
                BridgeAndCloseStreams(requestToBroker.InputStream, httpRequest.GetRequestStream());
            }

            return httpRequest;
        }

        /// <summary>
        /// Convert System.Net.Cookie into System.Web.HttpCookie
        /// </summary>
        private static HttpCookie CookieToHttpCookie(Cookie cookie)
        {
            HttpCookie httpCookie = new HttpCookie(cookie.Name);

            foreach (string value in cookie.Value.Split('&'))
            {
                string[] val = value.Split('=');
                httpCookie.Values.Add(val[0], val[1]);
            }

            httpCookie.Domain = cookie.Domain;
            httpCookie.Expires = cookie.Expires;
            httpCookie.HttpOnly = cookie.HttpOnly;
            httpCookie.Path = cookie.Path;
            httpCookie.Secure = cookie.Secure;

            return httpCookie;
        }

        /// <summary>
        /// Reads from stream into the to stream
        /// </summary>
        private static void BridgeAndCloseStreams(Stream from, Stream to)
        {
            try
            {
                int read;
                do
                {
                    read = from.ReadByte();

                    if (read != -1)
                    {
                        to.WriteByte((byte)read);
                    }
                }
                while (read != -1);
            }
            finally
            {
                from.Close();
                to.Close();
            }
        }
    }
}
View Code

 

posted @ 2022-02-24 18:10  江境纣州  阅读(19)  评论(0编辑  收藏  举报