﻿using System;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;


namespace app.icaiban.com
{
    public class httpModule : IHttpModule
    {


        /// <summary>
        /// 您将需要在您网站的 web.config 文件中配置此模块，
        /// 并向 IIS 注册此模块，然后才能使用。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpModule Members

        public void Dispose()
        {
            //此处放置清除代码。
        }

        public void Init(HttpApplication context)
        {
            //context.BeginRequest是开始处理HTTP管线请求时发生的事件
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }


        /// <summary>
        /// 获取服务器主机地址（包括访问协议方案、主机地址和端口号）。
        /// </summary>
        /// <value>服务器主机地址。</value>
        public static string GetHost()
        {

            Uri uri = HttpContext.Current.Request.Url;
            return String.Concat(uri.Scheme, "://", uri.Authority);

        }

        void context_BeginRequest(object sender, EventArgs e)
        {

            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            ICaiBan.Framework.IO.Log.DebugerWriteLog("app.icaiban.com", "request:" + context.Request.AppRelativeCurrentExecutionFilePath);

        
            string path = System.Configuration.ConfigurationManager.AppSettings[context.Request.AppRelativeCurrentExecutionFilePath];

            if (!string.IsNullOrWhiteSpace(path))
            {
                if (path.StartsWith("~/"))
                    path = context.Server.MapPath(path);


                ICaiBan.Framework.IO.Log.DebugerWriteLog("app.icaiban.com", "filename:" + path);

                context.Response.ContentType = "application/vnd.android.package-archive";

                System.IO.FileInfo fileInfo = new FileInfo(path);

                context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileInfo.Name));
                context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());

                //以字符流的形式下载文件    
                FileStream fs = new FileStream(path, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();

                context.Response.BinaryWrite(bytes);
                try { context.Response.Flush(); }
                catch { }
                finally
                {
                    System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
                } 


            }



        }


    



     


        #endregion
    }
}
