示例#1
0
        public static string RenderPartialFromPath(this IFubuPage page, string path)
        {
            RouteCollection routes = RouteTable.Routes;
            string originalPath = HttpContext.Current.Request.Path;
            HttpContext.Current.RewritePath(path);
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            RouteData data = routes.GetRouteData(httpContext);
            IHttpHandler httpHandler = data.RouteHandler.GetHttpHandler(new RequestContext(httpContext, data));
            httpHandler.ProcessRequest(HttpContext.Current);
            httpContext.RewritePath(originalPath, false);

            return "";
        }
        /// <summary>
        /// Determines whether node is accessible to user.
        /// </summary>
        /// <param name="controllerTypeResolver">The controller type resolver.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="context">The context.</param>
        /// <param name="node">The node.</param>
        /// <returns>
        /// 	<c>true</c> if accessible to user; otherwise, <c>false</c>.
        /// </returns>
        public bool IsAccessibleToUser(IControllerTypeResolver controllerTypeResolver, DefaultSiteMapProvider provider, HttpContext context, SiteMapNode node)
        {
            // Is security trimming enabled?
            if (!provider.SecurityTrimmingEnabled)
            {
                return true;
            }

            // Is it an external node?
            var nodeUrl = node.Url;
            if (nodeUrl.StartsWith("http") || nodeUrl.StartsWith("ftp"))
            {
                return true;
            }

            // Is it a regular node?
            var mvcNode = node as MvcSiteMapNode;
            if (mvcNode == null)
            {
                throw new AclModuleNotSupportedException(
                    Resources.Messages.AclModuleDoesNotSupportRegularSiteMapNodes);
            }

            // Clickable? Always accessible.
            if (mvcNode.Clickable == false)
            {
                return true;
            }

            // Time to delve into the AuthorizeAttribute defined on the node.
            // Let's start by getting all metadata for the controller...
            var controllerType = controllerTypeResolver.ResolveControllerType(mvcNode.Area, mvcNode.Controller);
            if (controllerType == null)
            {
                return false;
            }

            // Find routes for the sitemap node's url
            HttpContextBase httpContext = new HttpContextWrapper(context);
            string originalPath = httpContext.Request.Path;
            var originalRoutes = RouteTable.Routes.GetRouteData(httpContext);
            httpContext.RewritePath(nodeUrl, true);

            HttpContextBase httpContext2 = new HttpContext2(context);
            RouteData routes = mvcNode.GetRouteData(httpContext2);
            if (routes == null)
            {
                return true; // Static URL's will have no route data, therefore return true.
            }
            foreach (var routeValue in mvcNode.RouteValues)
            {
                routes.Values[routeValue.Key] = routeValue.Value;
            }
            if (!routes.Route.Equals(originalRoutes.Route) || originalPath != nodeUrl || mvcNode.Area == String.Empty)
            {
                routes.DataTokens.Remove("area");
                //routes.DataTokens.Remove("Namespaces");
                //routes.Values.Remove("area");
            }
            var requestContext = new RequestContext(httpContext, routes);

            // Create controller context
            var controllerContext = new ControllerContext();
            controllerContext.RequestContext = requestContext;
            try
            {
                string controllerName = requestContext.RouteData.GetRequiredString("controller");
                controllerContext.Controller = ControllerBuilder.Current.GetControllerFactory().CreateController(requestContext, controllerName) as ControllerBase;
            }
            catch
            {
                try
                {
                    controllerContext.Controller = Activator.CreateInstance(controllerType) as ControllerBase;
                }
                catch
                {
                }
            }

            ControllerDescriptor controllerDescriptor = null;
            if (typeof(IController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedControllerDescriptor(controllerType);
            }
            else if (typeof(IAsyncController).IsAssignableFrom(controllerType))
            {
                controllerDescriptor = new ReflectedAsyncControllerDescriptor(controllerType);
            }

            ActionDescriptor actionDescriptor = null;
            try
            {
                actionDescriptor = controllerDescriptor.FindAction(controllerContext, mvcNode.Action);
            }
            catch
            {
            }
            if (actionDescriptor == null)
            {
                actionDescriptor = controllerDescriptor.GetCanonicalActions().Where(a => a.ActionName == mvcNode.Action).FirstOrDefault();
            }

            // Verify security
            try
            {
                if (actionDescriptor != null)
                {
            #if NET35
                    IEnumerable<AuthorizeAttribute> authorizeAttributesToCheck =
                       actionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                           <AuthorizeAttribute>().ToList()
                           .Union(
                               controllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).OfType
                                   <AuthorizeAttribute>().ToList());
            #else
                    IEnumerable<AuthorizeAttribute> authorizeAttributesToCheck =
                        FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor)
                            .Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
                            .Select(f => f.Instance as AuthorizeAttribute);
            #endif

                    // Verify all attributes
                    foreach (var authorizeAttribute in authorizeAttributesToCheck)
                    {
                        try
                        {
                            var currentAuthorizationAttributeType = authorizeAttribute.GetType();

                            var builder = new AuthorizeAttributeBuilder();
                            var subclassedAttribute =
                                currentAuthorizationAttributeType == typeof(AuthorizeAttribute) ?
                                   new InternalAuthorize(authorizeAttribute) : // No need to use Reflection.Emit when ASP.NET MVC built-in attribute is used
                                   (IAuthorizeAttribute)builder.Build(currentAuthorizationAttributeType).Invoke(null);

                            // Copy all properties
                            ObjectCopier.Copy(authorizeAttribute, subclassedAttribute);

                            if (!subclassedAttribute.IsAuthorized(controllerContext.HttpContext))
                            {
                                return false;
                            }
                        }
                        catch
                        {
                            // do not allow on exception
                            return false;
                        }
                    }
                }

                // No objection.
                return true;
            }
            finally
            {
                // Restore HttpContext
                httpContext.RewritePath(originalPath, true);
            }
        }
示例#3
0
        /// <summary>
        /// Returns a response by executing the Error controller with the specified action.
        /// </summary>
        /// <param name="action">
        /// The action.
        /// </param>
        private void DisplayErrorPage(string action)
        {
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", action);

            this.Server.ClearError();
            this.Response.Clear();

            var httpContext = new HttpContextWrapper(this.Context);
            var requestContext = new RequestContext(httpContext, routeData);

            IController errorController =
                ControllerBuilder.Current.GetControllerFactory().CreateController(
                    new RequestContext(
                        httpContext,
                        routeData),
                    "Error");

            // Clear the query string, in particular to avoid HttpRequestValidationException being re-raised
            // when the error view is rendered by the Error Controller.
            httpContext.RewritePath(httpContext.Request.FilePath, httpContext.Request.PathInfo, string.Empty);

            errorController.Execute(requestContext);
        }
		/// <summary>
		/// Handles the Begin event of the request control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void context_BeginRequest(object sender, EventArgs e)
		{
			#region LoadApplicationRules Event

			if (Manager.ApplicationRulesNeedLoading)
			{
				// call load application rules
				var loadRulesArgs = new LoadRulesEventArgs();
				OnLoadApplicationRules(loadRulesArgs);

				Manager.LoadApplicationRules(loadRulesArgs);
			}

			#endregion

			var context = new HttpContextWrapper(((HttpApplication)sender).Context);
			var rewrittenUrl = Manager.RunRules(context);

			// make sure the rewrittenUrl returned is not null
			// a null value can indicate a proxy request
			if (rewrittenUrl != null)
			{
				// configure IIS7 for worker request
				// this will not do anything if the IIS7 worker request is not found
				Manager.ModifyIIS7WorkerRequest(context);

				// get the path and query for the rewritten URL
				string rewrittenUrlPath = rewrittenUrl.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);

				// rewrite path using new URL
				if (HttpRuntime.UsingIntegratedPipeline && Manager.Configuration.Rewriter.AllowIis7TransferRequest)
				{
					var request = context.Request;
					var headers = new NameValueCollection(context.Request.Headers);

					int transferCount = 1;
					string transferCountHeader = headers["X-Rewriter-Transfer"];
					if (!String.IsNullOrEmpty(transferCountHeader) && Int32.TryParse(transferCountHeader, out transferCount))
						transferCount++;

					headers["X-Rewriter-Transfer"] = transferCount.ToString(CultureInfo.InvariantCulture); 

					context.Server.TransferRequest(
						rewrittenUrlPath,
						true,
						request.HttpMethod,
						headers
					);
				}
				else
					context.RewritePath(rewrittenUrlPath, Manager.Configuration.Rewriter.RebaseClientPath);
			}
		}
		/// <summary>
		/// Handles the PostMapRequestHandler event of the context control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void context_PostMapRequestHandler(object sender, EventArgs e)
		{
			var context = new HttpContextWrapper(((HttpApplication)sender).Context);

			// check to see if this is a proxy request
			if (context.Items.Contains(Manager.ProxyHandlerStorageName))
			{
				var proxy = context.Items[Manager.ProxyHandlerStorageName] as IHttpProxyHandler;

				context.RewritePath("~" + proxy.ResponseUrl.PathAndQuery);
				context.Handler = proxy;
			}
		}
示例#6
0
        public void ProcessRequest(HttpContext ctx)
        {
            var context = new HttpContextWrapper(ctx);

            // Handle invalid requests where HTML encoding is passed in the querystring.
            context.RewritePath(context.Server.HtmlDecode(context.Request.Url.PathAndQuery));

            if (context.Request.GetString("path") == string.Empty)
                throw new Exception("'path' must be specified in the querystring.");

            if (context.Request.GetInteger("width") == int.MinValue && context.Request.GetInteger("height") == int.MinValue)
                throw new Exception("'width' or 'height' must be specified in the querystring.");

            _path = context.Request.GetString("path");
            _extension = Path.GetExtension(_path).Replace("jpg", "jpeg").Trim('.');
            _width = context.Request.GetInteger("width");
            _height = context.Request.GetInteger("height");
            _quality = context.Request.GetInteger("quality", 100);
            _cache = context.Request.GetBoolean("cache", true);
            _cacheFile = string.Format("{0}\\_cache\\{1}", context.Server.MapPath(Path.GetDirectoryName(_path)), Path.GetFileName(_path).Replace(".", string.Format("_w{0}_h{1}_q{2}.", _width, (_height == int.MinValue) ? 0 : _height, _quality)));

            // Default flip to true if width is set, otherwise default it to false
            if (_width != int.MinValue)
                _flip = context.Request.GetBoolean("flip", true);
            else
                _flip = context.Request.GetBoolean("flip", false);

            if (_width > 1500 || _height > 1500)
                throw new Exception("The maximum resize dimensions for width/height is 1500 pixels.");

            //if (_cache && File.Exists(_cacheFile))
            //{
            //    context.Response.WriteFile(_cacheFile);
            //}

            if (!File.Exists(_cacheFile))
            {
                MemoryStream memoryStream = null;
                try
                {
                    memoryStream = File.Exists(context.Server.MapPath(_path)) ?
                        ImageTools.ResizeImage(context.Server.MapPath(_path), _width, _height, _quality, _flip, _extension) :
                        ImageTools.GetSpacer(1, 1, System.Drawing.Color.Transparent);

                    PathTools.EnsureDirectory(Path.GetDirectoryName(_cacheFile));
                    memoryStream.Save(_cacheFile);
                }
                catch (Exception)
                {

                }
                finally
                {
                    memoryStream.Close();
                }
            }

            var lastModified = File.GetLastWriteTime(_cacheFile);
            lastModified = new DateTime(lastModified.Year, lastModified.Month, lastModified.Day, lastModified.Hour, lastModified.Minute, lastModified.Second);  // Remove milliseconds from file datestamp

            if (!String.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"]) && lastModified <= DateTime.Parse(context.Request.Headers["If-Modified-Since"]))
            {
                context.Response.StatusCode = 304;
                context.Response.StatusDescription = "Not Modified";
                context.Response.End();
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetLastModified(lastModified);
            context.Response.ContentType = "image/" + _extension;
            context.Response.WriteFile(_cacheFile);
            context.Response.End();
        }
        private void OnBeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication) sender;
            HttpContextBase context = new HttpContextWrapper(app.Context);
            string path = context.Request.Path;

            //
            // Check to see if we are dealing with a request for the "elmah.axd" handler
            // and if so, we need to rewrite the path!
            //

            int handlerPosition = path.IndexOf(_handlerPathWithForwardSlash, StringComparison.OrdinalIgnoreCase);

            if (handlerPosition >= 0)
                context.RewritePath(
                    path.Substring(0, handlerPosition + _handlerPathLength),
                    path.Substring(handlerPosition + _handlerPathLength),
                    context.Request.QueryString.ToString());
        }