⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cshttpmodule.cs

📁 本系统是在asp版《在线文件管理器》的基础上设计制作
💻 CS
字号:
//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.IO;
using System.Web;
using CommunityServer.Components;
using CommunityServer.Configuration;

namespace CommunityServer 
{

    // *********************************************************************
    //  CSHttpModule
    //
    /// <summary>
    /// This HttpModule encapsulates all the forums related events that occur 
    /// during ASP.NET application start-up, errors, and end request.
    /// </summary>
    // ***********************************************************************/
    public class CSHttpModule : IHttpModule 
    {
        #region Member variables and inherited properties / methods

        public String ModuleName 
        { 
            get { return "CSHttpModule"; } 
        }    


        // *********************************************************************
        //  ForumsHttpModule
        //
        /// <summary>
        /// Initializes the HttpModule and performs the wireup of all application
        /// events.
        /// </summary>
        /// <param name="application">Application the module is being run for</param>
        public void Init(HttpApplication application) 
        { 
            // Wire-up application events
            //
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            application.AuthenticateRequest += new EventHandler(Application_AuthenticateRequest);
            application.Error += new EventHandler(this.Application_OnError);
            application.AuthorizeRequest += new EventHandler(this.Application_AuthorizeRequest);
            
            //settingsID = SiteSettingsManager.GetSiteSettings(application.Context).SettingsID;
            Jobs.Instance().Start();
            //CSException ex = new CSException(CSExceptionType.ApplicationStart, "Appication Started " +  AppDomain.CurrentDomain.FriendlyName);
            //ex.Log();
        }

        //int settingsID;
        public void Dispose() 
        {
            //CSException ex = new CSException(CSExceptionType.ApplicationStop, "Application Stopping " +  AppDomain.CurrentDomain.FriendlyName);
            //ex.Log(settingsID);
            Jobs.Instance().Stop();
        }

		#region Installer




		#endregion


        #endregion

        #region Application OnError
        private void Application_OnError (Object source, EventArgs e) 
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            
			CSException csException = context.Server.GetLastError() as CSException;

			if(csException == null)
				csException = context.Server.GetLastError().GetBaseException() as CSException;

			try
			{
				if (csException != null)
				{
					switch (csException.ExceptionType) 
					{
						case CSExceptionType.UserInvalidCredentials:
						case CSExceptionType.AccessDenied:
						case CSExceptionType.AdministrationAccessDenied:
						case CSExceptionType.ModerateAccessDenied:
						case CSExceptionType.PostDeleteAccessDenied:
						case CSExceptionType.PostProblem:
						case CSExceptionType.UserAccountBanned:
						case CSExceptionType.ResourceNotFound:
						case CSExceptionType.UserUnknownLoginError:
						case CSExceptionType.SectionNotFound:
							csException.Log();
							break;
					}
				} 
				else 
				{
					Exception ex = context.Server.GetLastError();
					if(ex.InnerException != null)
						ex = ex.InnerException;

					csException = new CSException(CSExceptionType.UnknownError, ex.Message, context.Server.GetLastError());

                    System.Data.SqlClient.SqlException sqlEx = ex as System.Data.SqlClient.SqlException;
                    if(sqlEx == null || sqlEx.Number != -2) //don't log time outs
    					csException.Log();
				}
			}
			catch{} //not much to do here, but we want to prevent infinite looping with our error handles

			CSEvents.CSException(csException);
        }


        #endregion


        #region Application AuthenticateRequest

        private void Application_AuthenticateRequest(Object source, EventArgs e) 
        {
            HttpContext context = HttpContext.Current;
            Provider p = null;
            ExtensionModule module = null;

			// If the installer is making the request terminate early
			if (CSConfiguration.GetConfig().AppLocation.CurrentApplicationType == ApplicationType.Installer) {
				return;
			}
			
			// Only continue if we have a valid context
            //
            if ((context == null) || (context.User == null))
                return;

            try 
            {
                // Logic to handle various authentication types
                //
				switch(context.User.Identity.GetType().Name.ToLower())
				{

                        // Microsoft passport
					case "passportidentity":
						p = (Provider) CSConfiguration.GetConfig().Extensions["PassportAuthentication"];
                        module = ExtensionModule.Instance(p);
						if(module != null)
							module.ProcessRequest();
						else
							goto default;
						break;

                        // Windows
					case "windowsidentity":
						p = (Provider) CSConfiguration.GetConfig().Extensions["WindowsAuthentication"];
                        module = ExtensionModule.Instance(p);
						if(module != null)
							module.ProcessRequest();
						else
							goto default;
						break;

						// Forms
					case "formsidentity":
						p = (Provider) CSConfiguration.GetConfig().Extensions["FormsAuthentication"];
						module = ExtensionModule.Instance(p);
						if(module != null)
							module.ProcessRequest();
						else
							goto default;
						break;

						// Custom
					case "customidentity":
						p = (Provider) CSConfiguration.GetConfig().Extensions["CustomAuthentication"];
						module = ExtensionModule.Instance(p);
						if(module != null)
							module.ProcessRequest();
						else
							goto default;
						break;

                    default:
                        CSContext.Current.UserName = context.User.Identity.Name;
                        break;

                }

            } 
            catch( Exception ex ) 
            {
                CSException forumEx = new CSException( CSExceptionType.UnknownError, "Error in AuthenticateRequest", ex );
                forumEx.Log();

                throw forumEx;
            }

            //			// Get the roles the user belongs to
            //			//
            //			Roles roles = new Roles();
            //			roles.GetUserRoles();
        }
        #endregion

        #region Application AuthorizeRequest
        private void Application_AuthorizeRequest (Object source, EventArgs e) {


			if (CSConfiguration.GetConfig().AppLocation.CurrentApplicationType == ApplicationType.Installer)
			{
				//CSContext.Create(context);
				return;
			}


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

			CSContext csContext = CSContext.Current;
            //bool enableBannedUsersToLogin = CSContext.Current.SiteSettings.EnableBannedUsersToLogin;
            
//			// If the installer is making the request terminate early
//			if (csContext.ApplicationType == ApplicationType.Installer) {
//				return;
//			}

            //csContext.User = CSContext.Current.User;

			CSEvents.UserKnown(csContext.User);

            ValidateApplicationStatus(csContext);

            // Track anonymous users
            //
			Users.TrackAnonymousUsers(context);

            // Do we need to force the user to login?
            //
			
            if (context.Request.IsAuthenticated) {
                string username = context.User.Identity.Name;
                if (username != null) {
                    string[] roles = CommunityServer.Components.Roles.GetUserRoleNames(username);
                    if (roles != null && roles.Length > 0) {
                        csContext.RolesCacheKey = string.Join(",",roles);
                    }
                }
            }
        }

        #endregion

        #region Application BeginRequest
		private void Application_BeginRequest(Object source, EventArgs e) 
		{
			HttpApplication application = (HttpApplication)source;
			HttpContext context = application.Context;

			
			CSConfiguration config = CSConfiguration.GetConfig();
			
			// If the installer is making the request terminate early
			if (config.AppLocation.CurrentApplicationType == ApplicationType.Installer)
			{
				//CSContext.Create(context);
				return;
			}

			CheckWWWStatus(config,context);

			

			CSContext.Create(context, ReWriteUrl(context));

									
		}

		private void CheckWWWStatus(CSConfiguration config, HttpContext context)
		{
			if(config.WWWStatus == WWWStatus.Ignore)
				return;

			const string withWWW = "http://www.";
			const string noWWW = "http://";
			string rawUrl = context.Request.Url.ToString().ToLower();
			bool isWWW = rawUrl.StartsWith(withWWW);

			
			if(config.WWWStatus == WWWStatus.Remove && isWWW)
			{
				context.Response.Redirect(rawUrl.Replace(withWWW, noWWW));
			}
			else if(config.WWWStatus == WWWStatus.Require && !isWWW)
			{
				context.Response.Redirect(rawUrl.Replace(noWWW, withWWW));
			}
			
		
		}

		#region ReWriteUrl
		private bool ReWriteUrl(HttpContext context)
		{

			// we're now allowing each individual application to be turned on and off individually. So before we allow
			// a request to go through we need to check if this product is disabled and the path is for the disabled product,
			// if so we display the disabled product page.
			//
			// I'm also allowing the page request to go through if the page request is for an admin page. In the past if you 
			// disabled the forums you were locked out, now with this check, even if you're not on the same machine but you're accessing
			// an admin path the request will be allowed to proceed, where the rest of the checks will ensure that the user has the
			// permission to access the specific url.

			// Url Rewriting
			//
			//RewriteUrl(context);

			string newPath = null;
			string path = context.Request.Path;
			bool isReWritten = SiteUrls.RewriteUrl(path,context.Request.Url.Query,out newPath);

			//very wachky. The first call into ReWritePath always fails with a 404.
			//calling ReWritePath twice actually fixes the probelm as well. Instead, 
			//we use the second ReWritePath overload and it seems to work 100% 
			//of the time.
			if(isReWritten && newPath != null)
			{
				string qs = null;
				int index = newPath.IndexOf('?');
				if (index >= 0)
				{
					qs = (index < (newPath.Length - 1)) ? newPath.Substring(index + 1) : string.Empty;
					newPath = newPath.Substring(0, index);
				}
				context.RewritePath(newPath,null,qs);
			}

			return isReWritten;
		}

		#endregion

        private void ValidateApplicationStatus(CSContext cntx)
        {
            if(!cntx.User.IsAdministrator)
            {
                string disablePath = null;
                switch(cntx.Config.AppLocation.CurrentApplicationType)
                {
                    case ApplicationType.Forum:
                        if(cntx.SiteSettings.ForumsDisabled)
                            disablePath = "ForumsDisabled.htm";
                        break;
                    case ApplicationType.Weblog:
                        if(cntx.SiteSettings.BlogsDisabled)
                            disablePath = "BlogsDisabled.htm";
                        break;
                    case ApplicationType.Gallery:
                        if(cntx.SiteSettings.GalleriesDisabled)
                            disablePath = "GalleriesDisabled.htm";
                        break;
                    case ApplicationType.GuestBook:
                        if(cntx.SiteSettings.GuestBookDisabled)
                            disablePath = "GuestBookDisabled.htm";
                        break;
                }

                if(disablePath != null)
                {

                    string errorpath = cntx.Context.Server.MapPath(string.Format("~/Languages/{0}/errors/{1}",cntx.Config.DefaultLanguage,disablePath));
                    using(StreamReader reader = new StreamReader(errorpath))
                    {
                        string html = reader.ReadToEnd();
                        reader.Close();

                        cntx.Context.Response.Write(html);
                        cntx.Context.Response.End();
                    }
                }
            }
        }

        #endregion


    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -