示例#1
0
 /// <summary>
 /// Executes all requets as JSON method/arg pairs
 /// </summary>
 /// <param name="adminMode">if set to <c>true</c> [Admin mode].</param>
 /// <returns></returns>
 internal static string ExecuteJSONResponders(bool adminMode)
 {
     HttpContext current = HttpContext.Current;
     HttpRequest request = HttpContext.Current.Request;
     HttpResponse response = HttpContext.Current.Response;
     string requestContentType = request.ContentType;
     int requestLength = request.TotalBytes;
     int requestCount = 0;
     int querystringCount = 0;
     DateTime start = new DateTime();
     start = DateTime.Now;
     Dictionary<string, object> j = new Dictionary<string, object>();
     requestCount = request.Form.Count;
     querystringCount = request.QueryString.Count;
     for(var x = 0; requestCount > x; x++) {
         string keyName = request.Form.GetKey(x);
         if(keyName.StartsWith(Main.MethodKey)) {
             j.Add(keyName, JsonToMethod(request.Form[x], adminMode));
         }
     }
     for(var x = 0; querystringCount > x; x++) {
         string keyName = request.QueryString.GetKey(x);
         if(keyName != null) {
             if(keyName.StartsWith(Main.MethodKey)) {
                 j.Add(keyName, JsonToMethod(request.QueryString[x], adminMode));
             }
         }
     }
     if(j.Count > 0) {
         /* if there is a file present output the file instead of the json string */
         foreach(KeyValuePair<string, object> field in j) {
             Dictionary<string, object> innerFields = (Dictionary<string, object>)field.Value;
             foreach(KeyValuePair<string, object> innerField in innerFields) {
                 if(innerField.Value != null) {
                     if(innerField.Value.GetType() == typeof(Dictionary<string, object>)) {
                         Dictionary<string, object> iiFields = (Dictionary<string, object>)innerField.Value;
                         if(iiFields.ContainsKey("fileName")) {
                             string content = (string)iiFields["content"].ToString();
                             response.ContentType = (string)iiFields["contentType"];
                             response.Write(content);
                             response.AddHeader("Content-Disposition", "attachment; filename=\"" + (string)iiFields["fileName"] + "\"");
                             response.AddHeader("Content-Length", content.Length.ToString());
                             response.Flush();
                             current.ApplicationInstance.CompleteRequest();
                             /* only allowed to output one file at a time */
                             return "";
                         }
                     }
                 }
             }
         }
         if(Main.Site != null) {
             EndRequestEventArgs f = new EndRequestEventArgs(Main.GetCurrentSession(), current);
             Main.Site.raiseOnendrequest(f);
         }
         return j.ToJson();
     } else {
         if(Main.Site != null) {
             EndRequestEventArgs f = new EndRequestEventArgs(Main.GetCurrentSession(), current);
             Main.Site.raiseOnendrequest(f);
         }
         return "";
     }
 }
示例#2
0
 /// <summary>
 /// Raises the onendrequest event.
 /// </summary>
 /// <param name="args">The <see cref="Rendition.EndRequestEventArgs"/> instance containing the event data.</param>
 internal void raiseOnendrequest( EndRequestEventArgs args )
 {
     if( EndRequest != null ) { EndRequest( this, args ); };
 }
        /// <summary>
        /// Process JSON messages.
        /// Map some messages to methods.
        /// Map some messages to embedded resources.
        /// Secondary HTTP Pipeline.
        /// </summary>
        /// <param name="httpApp">The Http app.</param>
        /// <returns>When true, a AJAX responder was called</returns>
        private static bool processHTTPRequest(HttpApplication httpApp)
        {
            /* get the current http context */
            bool _JSONResponse = false;
            HttpContext current = HttpContext.Current;
            /* start a Timer */
            DateTime startHTTPRequest = DateTime.Now;
            current.Items.Add("startHTTPRequest", startHTTPRequest);
            /* create a reference to the session object */
            Session session = null;
            string executionFilePath = current.Request.AppRelativeCurrentExecutionFilePath;
            bool _isVirtualResourcePath = IsVirtualResourcePath(executionFilePath);
            /* ***1*** make sure user's don't request an invalid file resource by redirecting */
            if(Main.AdminDirectory == executionFilePath) {
                current.Response.Redirect(Main.AdminDirectory + "/", false);
                current.ApplicationInstance.CompleteRequest();
                goto End;
            }
            /* ***2*** if this is not a request for a /Admin or /responder directory
             * implement the rewriter directives */
            if(!_isVirtualResourcePath) {
                /* try to redirect the URL */
                if(redirectUrl(current)) { goto End; };
                /* try to rewrite the URL */
                if(RewriteUrl(current)) { goto End; };
                /* site section rewrites */
                if(RewriteSiteSection(current)) { goto End; };
                /* check for category rewrites */
                if(RewriteCategory(current)) { goto End; };
                /* check for item rewrites */
                if(RewriteItem(current)) { goto End; };
            }
            /* ***3*** don't try and examine the physical path until _after_ the rewrite */
            string physicalPath = current.Request.PhysicalPath;
            bool _isResourceFile = IsResourceFile(physicalPath);

            /* if this is an image or other non dynamic resource file
             * and not used in a virtual path than don't do any further processing */
            if(_isResourceFile && !_isVirtualResourcePath) {
                sendNeverExpiresHeaders();
                goto End;
            }
            /* if this is a public resource, give up the resource now */
            foreach(string file in Main.PublicFiles) {
                if(executionFilePath == file || executionFilePath.StartsWith(Main.AdminDirectory + "/img")) {
                    sendNeverExpiresHeaders();
                    getResxResource(current);
                    goto End;
                }
            }
            /* no rewrite or redirect so now check if the file exists */
            if(!File.Exists(physicalPath) && !_isVirtualResourcePath) {
                ErrorPage(current, 404, String.Format("Cannot find {0}", physicalPath));
                goto End;
            }
            /* the file or resource exists (probably)
             * create a Session
             * this is resource consuming */
            session = new Session(Site);
            /* place the session object in an object that is only good as long as the http pipeline lasts */
            current.Items.Add("currentSession", session);
            /* raise the after authentication event */
            AfterAuthenticationEventArgs args = new AfterAuthenticationEventArgs(session, current);
            Main.Site.raiseOnAfterAuthentication(args);
            /* execute AJAX responders - if a responder was executed then end. */
            try {
                if(executeResponders(current, session)) {
                    _JSONResponse = true;
                    goto End;
                };
            } catch(Exception ex) {
                String.Format("executeResponders exception =>{0}", ex.Message).Debug(0);
                goto End;
            }
            /* check if this is a request for the Admin directory or Admin responder virtual page */
            if(_isVirtualResourcePath) {
                /* don't do anything for people who arn't logged on as administrators, unless we're in setup mode */
                if(!session.Administrator) {
                    /* 401 forbidden, and ask for a username / password */
                    /* RFC 2617 HTTP Authentication: Basic and Digest Access Authentication */
                    if(current.Request.Headers["Authorization"] != null) {
                        /* user is sending logon attempt via HTTP auth */
                        string _raw_header = current.Request.Headers["Authorization"];
                        string[] _hprams = _raw_header.Split(' ');
                        string method = _hprams[0];
                        string enc_auth = _hprams[1];
                        /* decode base 64 auth string */
                        string _raw_auth = Encoding.ASCII.GetString(Convert.FromBase64String(enc_auth));
                        string[] _auth = _raw_auth.Split(':');
                        string userName = _auth[0];
                        string password = _auth[1];
                        /* try to logon using the provided authentication creditials */
                        if(session.LogOn(userName, password) == 0) {
                            session.Refresh();
                        }
                    }
                    /* check again */
                    if(!session.Administrator) {
                        if(!UseFormsBasedAuth) {
                            current.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", current.Request.Url.DnsSafeHost));
                            ErrorPage(current, 401,
                            String.Format("Only administrators can access the {0} virtual directory.", Main.AdminDirectory));/* 401 unauthorized */
                            current.ApplicationInstance.CompleteRequest();
                            goto End;
                        } else {
                            current.Response.Redirect(Main.PublicDirectory + "/logon.html?rdr=" + executionFilePath.UrlEncode());
                            current.ApplicationInstance.CompleteRequest();
                            goto End;
                        }
                    }
                }
                sendNeverExpiresHeaders();
                /* if this is a request for the Admin directory tree respond with the given Admin resource */
                if(!executionFilePath.Contains(Main.AdminResponder)) {
                    getResxResource(current);
                    goto End;
                }
            }
            End:
            /* fire off events */
            EndRequestEventArgs endRequestargs = new EndRequestEventArgs(session, current);
            Site.raiseOnendrequest(endRequestargs);
            DateTime endHTTPRequest = DateTime.Now;
            current.Items.Add("finish_processHTTPRequest", endHTTPRequest);
            return _JSONResponse;
        }