示例#1
0
        protected internal virtual IAsyncResult BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, object state)
        {
            AddVersionHeader(httpContext);

            // Get the controller type
            string controllerName = RequestContext.RouteData.GetRequiredString("controller");

            // Instantiate the controller and call Execute
            IControllerFactory factory    = ControllerBuilder.GetControllerFactory();
            IController        controller = factory.CreateController(RequestContext, controllerName);

            if (controller == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentUICulture,
                              MvcResources.ControllerBuilder_FactoryReturnedNull,
                              factory.GetType(),
                              controllerName));
            }

            BeginExecuteDelegate beginExecute;
            EndExecuteDelegate   endExecute;

            IAsyncController asyncController = controller as IAsyncController;

            if (asyncController != null)
            {
                beginExecute = asyncController.BeginExecute;
                endExecute   = asyncController.EndExecute;
            }
            else
            {
                // execute synchronous controller asynchronously
                ExecuteDelegate executeDelegate = rc => SynchronizationContext.Sync(() => controller.Execute(rc));
                beginExecute = executeDelegate.BeginInvoke;
                endExecute   = executeDelegate.EndInvoke;
            }

            BeginInvokeCallback beginCallback = (innerCallback, innerState) => {
                try {
                    return(beginExecute(RequestContext, innerCallback, innerState));
                }
                catch {
                    factory.ReleaseController(controller);
                    throw;
                }
            };

            AsyncCallback endCallback = ar => {
                try {
                    endExecute(ar);
                }
                finally {
                    factory.ReleaseController(controller);
                }
            };

            return(AsyncResultWrapper.Wrap(callback, state, beginCallback, endCallback, _processRequestTag));
        }
        protected virtual IAsyncResult BeginProcessRequest(
            HttpContextBase context, AsyncCallback callback, object state)
        {
            AppendVersionHeader(context);
            string controllerName = Context.RouteData.GetRequiredValue <string>("controller");

            IControllerFactory factory    = Builder.GetControllerFactory();
            IController        controller = factory.CreateController(Context, controllerName);

            if (controller == null)
            {
                throw Error.CouldNotCreateController(controllerName);
            }

            IAsyncController asyncController = (controller as IAsyncController);

            if (asyncController == null)             // synchronous controller
            {
                Action action = delegate {
                    try
                    {
                        controller.Execute(Context);
                    }
                    finally
                    {
                        factory.ReleaseController(controller);
                    }
                };
                return(AsyncResultWrapper.BeginSynchronous(callback, state, action, _tag));
            }

            // asynchronous controller
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) {
                try
                {
                    return(asyncController.BeginExecute(Context, asyncCallback, asyncState));
                }
                finally
                {
                    factory.ReleaseController(asyncController);
                }
            };
            EndInvokeDelegate endDelegate = delegate(IAsyncResult asyncResult) {
                try
                {
                    asyncController.EndExecute(asyncResult);
                }
                finally
                {
                    factory.ReleaseController(asyncController);
                }
            };

            return(AsyncResultWrapper.Begin(AsyncTask.WrapCallbackForSynchronizedExecution(callback,
                                                                                           SynchronizationContextExtensions.GetSynchronizationContext()),
                                            state, beginDelegate, endDelegate, _tag));
        }
示例#3
0
        protected internal virtual void ProcessRequest(HttpContextBase httpContext)
        {
            AddVersionHeader(httpContext);

            // Get the controller type
            string controllerName = RequestContext.RouteData.GetRequiredString("controller");

            // Instantiate the controller and call Execute
            IControllerFactory factory    = ControllerBuilder.GetControllerFactory();
            IController        controller = factory.CreateController(RequestContext, controllerName);

            if (controller == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentUICulture,
                              MvcResources.ControllerBuilder_FactoryReturnedNull,
                              factory.GetType(),
                              controllerName));
            }
            try {
                controller.Execute(RequestContext);
            }
            finally {
                factory.ReleaseController(controller);
            }
        }
示例#4
0
        protected override void OnInit(EventArgs e)
        {
            string requiredString = this.RequestContext.RouteData.GetRequiredString("controller");

            IControllerFactory controllerFactory = this.ControllerBuilder.GetControllerFactory();

            IController controller = controllerFactory.CreateController(this.RequestContext, requiredString);

            if (controller == null)
            {
                throw new InvalidOperationException("Could not find controller: " + requiredString);
            }

            try
            {
                ControllerBase    controllerInst    = controller as ControllerBase;
                ControllerContext controllerContext = new ControllerContext(RequestContext, controllerInst);
                controller.Execute(controllerContext.RequestContext);
            }
            finally
            {
                controllerFactory.ReleaseController(controller);
            }

            this.Context.ApplicationInstance.CompleteRequest();
        }
示例#5
0
        private void gotoController(string controllerName, string action = null)
        {
            IController        controller = null;
            IControllerFactory factory    = null;

            try
            {
                factory    = ControllerBuilder.Current.GetControllerFactory();
                controller = factory.CreateController(RequestContext, controllerName);
                if (controller != null)
                {
                    RequestContext.RouteData.Values["controller"] = controllerName;
                    if (action != null)
                    {
                        RequestContext.RouteData.Values["action"] = action;
                    }
                    controller.Execute(RequestContext);
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.ToString());
            }
            finally
            {
                factory.ReleaseController(controller);
            }
        }
示例#6
0
        protected virtual void Include(string controllerName,
                                       string actionName, ValueDictionary arguments)
        {
            IControllerFactory factory =
                ControllerBuilder.Instance.GetControllerFactory();
            IController controller = null;

            try
            {
                controller = factory.CreateController(Context, controllerName);
                Controller c = (controller as Controller);
                Precondition.Require(c, () => Error.TargetMustSubclassController(controllerName));

                using (ChildContextOperator child = c.InitializeChildRequest(Context))
                {
                    if (!c.ActionExecutor.InvokeAction(c.Context, actionName, arguments))
                    {
                        c.HandleUnknownAction(actionName);
                    }
                }
            }
            catch (HttpException ex)
            {
                if (ex.GetHttpCode() == 500)
                {
                    throw;
                }

                throw Error.ChildRequestExecutionError(ex);
            }
            finally
            {
                factory.ReleaseController(controller);
            }
        }
示例#7
0
        /// <summary>
        /// Gets the page, and based on the Class of the Page, attempts to get the Dynamic routing information and processes.
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var node = mDynamicRouteHelper.GetPage(AddPageToCacheDependency: false);

            var routePair = ResolveRouteValues(node);

            RequestRoutingEventArgs RequestArgs = new RequestRoutingEventArgs()
            {
                Page                  = node,
                Configuration         = routePair,
                CurrentRequestContext = RequestContext
            };

            // Use event to allow users to overwrite the Dynamic Routing Data
            using (var RequestRoutingHandler = DynamicRoutingEvents.RequestRouting.StartEvent(RequestArgs))
            {
                // Check if the OutputCache was disabled or enabled during the event args
                if (routePair.ControllerName.Equals("DynamicRouteCached", StringComparison.InvariantCultureIgnoreCase) && !routePair.UseOutputCaching)
                {
                    routePair.ControllerName = "DynamicRoute";
                }
                else if (routePair.ControllerName.Equals("DynamicRoute", StringComparison.InvariantCultureIgnoreCase) && routePair.UseOutputCaching)
                {
                    routePair.ControllerName = "DynamicRouteCached";
                }

                // Handle passing the Include In Output Cache
                switch (routePair.ControllerName.ToLower())
                {
                case "dynamicroute":
                case "dynamicroutecached":
                case "dynamicroutetemplate":
                    RequestArgs.CurrentRequestContext.RouteData.Values["IncludeDocumentInOutputCache"] = routePair.IncludeDocumentInOutputCache;
                    break;
                }

                // Setup routing with new values
                RequestArgs.CurrentRequestContext.RouteData.Values["Controller"] = routePair.ControllerName;
                RequestArgs.CurrentRequestContext.RouteData.Values["Action"]     = routePair.ActionName;

                foreach (string Key in routePair.RouteValues.Keys)
                {
                    RequestArgs.CurrentRequestContext.RouteData.Values[Key] = routePair.RouteValues[Key];
                }

                // Allow users to adjust the RequestContext further
                RequestRoutingHandler.FinishEvent();

                // Pass back context
                RequestContext = RequestArgs.CurrentRequestContext;
            }

            IControllerFactory factory    = ControllerBuilder.Current.GetControllerFactory();
            IController        controller = factory.CreateController(RequestContext, routePair.ControllerName);

            controller.Execute(RequestContext);

            factory.ReleaseController(controller);
        }
        /// <summary>
        /// Cleans up the controller by releasing it using the controller factory, and by disposing it.
        /// </summary>
        private static void CleanupController(IController controller, IControllerFactory factory)
        {
            if (controller != null)
            {
                factory.ReleaseController(controller);
            }

            if (controller != null)
            {
                controller.DisposeIfDisposable();
            }
        }
        public static bool IsCurrentUserAuthorizedForRoute(this UrlHelper url, string routeName, RouteValueDictionary routeValues, HttpVerbs requestVerb)
        {
            string controllerName, actionName;

            if (routeValues.ContainsKey("controller"))
            {
                controllerName = (string)routeValues["controller"];
            }
            else
            {
                controllerName = url.RequestContext.RouteData.GetRequiredString("controller");
            }

            if (routeValues.ContainsKey("action"))
            {
                actionName = (string)routeValues["action"];
            }
            else
            {
                actionName = url.RequestContext.RouteData.GetRequiredString("action");
            }

            IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
            FakeHttpContext    httpContext       = new FakeHttpContext(url.RouteUrl(routeName, routeValues), url.RequestContext.HttpContext.User, requestVerb);
            RequestContext     requestContext    = new RequestContext(httpContext, url.RouteCollection.GetRouteData(httpContext));
            IController        controller        = controllerFactory.CreateController(requestContext, controllerName);

            if (controller == null)
            {
                throw new InvalidOperationException("The ControllerFactory did not return a Controller!");
            }
            try
            {
                IActionAuthorizationTestable testableController = controller as IActionAuthorizationTestable;
                Controller controllerImpl = controller as Controller;
                if (testableController == null && controllerImpl != null && controllerImpl.ActionInvoker.GetType() == typeof(ControllerActionInvoker))
                {
                    return(new ExposedControllerActionInvoker().IsAuthorizedForAction(new ControllerContext(requestContext, controllerImpl), actionName));
                }

                if (testableController == null)
                {
                    throw new NotSupportedException("Cannot look up the action method called by the route specified.\r\nThe ControllerFactory did not create an IController inherited from type Controller that uses a ControllerActionInvoker.\r\nTo overcome this, implement the IActionAuthorizationTestable interface on your controllers.");
                }

                return(testableController.IsAuthorizedForAction(httpContext.User, routeName, routeValues, requestVerb));
            }
            finally
            {
                controllerFactory.ReleaseController(controller);
            }
        }
示例#10
0
        public async override Task InvokeAsync()
        {
            var controller = _controllerFactory.CreateController(ActionContext);

            try
            {
                ActionContext.Controller = controller;
                await base.InvokeAsync();
            }
            finally
            {
                _controllerFactory.ReleaseController(ActionContext.Controller);
            }
        }
示例#11
0
        private void ExecuteRequest(RequestContext requestContext, DirectRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request", DirectResources.Common_DirectRequestIsNull);
            }

            HttpContextBase httpContext = requestContext.HttpContext;
            RouteData       routeData   = requestContext.RouteData;

            routeData.Values["controller"] = request.Action;
            routeData.Values["action"]     = request.Method;
            httpContext.Items[DirectRequest.DirectRequestKey] = request;
            var controller = (Controller)_factory.CreateController(requestContext, request.Action);

            DirectAction action = GetAction(request.Action);

            if (action == null)
            {
                throw new NullReferenceException(String.Format(DirectResources.DirectProvider_ActionNotFound, request.Action));
            }

            DirectMethod method = action.GetMethod(request.Method);

            if (method == null)
            {
                throw new NullReferenceException(String.Format(DirectResources.DirectProvider_MethodNotFound, request.Method, action.Name));
            }

            if (!method.IsFormHandler && method.Params == null)
            {
                if (request.Data == null && method.Len > 0 || request.Data != null && request.Data.Length != method.Len)
                {
                    throw new ArgumentException(String.Format(DirectResources.DirectProvider_WrongNumberOfArguments, request.Method, request.Action));
                }
            }

            try {
                controller.ActionInvoker = new DirectMethodInvoker();
                (controller as IController).Execute(requestContext);
            } catch (DirectException exception) {
                var errorResponse = new DirectErrorResponse(request, exception);
                errorResponse.Write(httpContext.Response);
            } finally {
                _factory.ReleaseController(controller);
            }

            httpContext.Items.Remove(DirectRequest.DirectRequestKey);
        }
 /// <summary>
 /// Enables processing of the result of an action method by a custom type that inherits from <see cref="T:System.Web.Mvc.ActionResult"/>.
 /// </summary>
 /// <param name="context"/>
 public override void ExecuteResult(ControllerContext context)
 {
     try
     {
         context = BuildPageControllerContext(context);
         actionInvoker.InvokeAction(context, "Index");
     }
     finally
     {
         if (context.Controller != null)
         {
             controllerFactory.ReleaseController(context.Controller);
         }
     }
 }
示例#13
0
        /// <summary>
        /// Gets a controller type by the name
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="requestContext"></param>
        /// <param name="controllerName"></param>
        /// <returns></returns>
        /// <remarks>
        /// This is related to issue: http://issues.umbraco.org/issue/U4-1726. We already have a method called GetControllerTypeInternal on our MasterControllerFactory,
        /// however, we cannot always guarantee that the usage of this will be a MasterControllerFactory like during unit tests. So we needed to create
        /// this extension method to do the checks instead.
        /// </remarks>
        internal static Type GetControllerTypeInternal(this IControllerFactory factory, RequestContext requestContext, string controllerName)
        {
            if (factory is MasterControllerFactory controllerFactory)
            {
                return(controllerFactory.GetControllerTypeInternal(requestContext, controllerName));
            }

            //we have no choice but to instantiate the controller
            var instance       = factory.CreateController(requestContext, controllerName);
            var controllerType = instance?.GetType();

            factory.ReleaseController(instance);

            return(controllerType);
        }
示例#14
0
        private static void DisposeController(IController controller, IControllerFactory factory)
        {
            if (controller != null)
            {
                factory.ReleaseController(controller);
            }

            if (controller == null)
            {
                return;
            }

            var disposable = controller as IDisposable;

            disposable?.Dispose();
        }
示例#15
0
        public async override Task InvokeAsync()
        {
            var controller = _controllerFactory.CreateController(ActionContext);

            try
            {
                ActionContext.Controller      = controller;
                ActionContext.InputFormatters = _inputFormattersProvider.InputFormatters
                                                .ToList();
                await base.InvokeAsync();
            }
            finally
            {
                _controllerFactory.ReleaseController(ActionContext.Controller);
            }
        }
示例#16
0
        public void ReleaseController(IController controller)
        {
            IControllerFactory factory = HttpContext.Current.Items[this._key] as IControllerFactory;

            if (factory == this)
            {
                IDisposable disposable = controller as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            else if (factory != null)
            {
                factory.ReleaseController(controller);
            }
        }
        public void ProcessRequest(HttpContextBase httpContext, IControllerFactory controllerFactory, string controllerName)
        {
            RequestContext requestContext = this.CreateRequestContext(httpContext, controllerName);
            IController controller = this.CreateController(controllerFactory, requestContext, controllerName);
            if (controller == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cannot find a controller with name '{0}'.", controllerName));
            }

            try
            {
                controller.Execute(requestContext);
            }
            finally
            {
                controllerFactory.ReleaseController(controller);
            }
        }
示例#18
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string             controllerId = RequestContext.RouteData.GetRequiredString("controller");
            IController        controller   = null;
            IControllerFactory factory      = null;

            try
            {
                factory    = ControllerBuilder.Current.GetControllerFactory();
                controller = factory.CreateController(RequestContext, controllerId);

                if (controller != null)
                {
                    controller.Execute(RequestContext);
                }
            }
            finally
            {
                factory.ReleaseController(controller);
            }
        }
示例#19
0
        public void ProcessRequest(HttpContext context)
        {
            //选择控制器工厂
            IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();

            //创建控制器实例
            IController controller = controllerFactory.CreateController(request, request.Controller);

            try
            {
                //执行
                controller.Execute(request);
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
            finally
            {
                controllerFactory.ReleaseController(controller);
            }
        }
示例#20
0
        protected virtual void ProcessRequest(HttpContextBase context)
        {
            AppendVersionHeader(context);
            string controllerName = _context.RouteData.GetRequiredValue <string>("controller");

            IControllerFactory factory    = Builder.GetControllerFactory();
            IController        controller = factory.CreateController(Context, controllerName);

            if (controller == null)
            {
                throw Error.CouldNotCreateController(controllerName);
            }

            try
            {
                controller.Execute(Context);
            }
            finally
            {
                factory.ReleaseController(controller);
            }
        }
        /// <summary>
        /// Process the current HTTP request.
        /// </summary>
        /// <param name="httpContext">The HttpContext containing the request.</param>
        public void ProcessRequest(HttpContext httpContext)
        {
            var controller = _requestContext.RouteData.GetRequiredString("controller");
            var action     = string.Empty;

            if (_requestContext.RouteData.Values["action"] != null)
            {
                action = _requestContext.RouteData.Values["action"].ToString();
            }

            if (action != string.Empty)
            {
                IController        viewController    = null;
                IControllerFactory controllerFactory = null;

                try
                {
                    controllerFactory = ControllerBuilder.Current.GetControllerFactory();

                    try
                    {
                        viewController = controllerFactory.CreateController(_requestContext, controller);
                        viewController.Execute(_requestContext);
                    }
                    catch
                    {
                        DispatchRequest(controllerFactory, controller, action);
                    }
                }
                finally
                {
                    if (controllerFactory != null)
                    {
                        controllerFactory.ReleaseController(viewController);
                    }
                }
            }
        }
示例#22
0
        /// <summary>
        /// Gets the page, and based on the Class of the Page, attempts to get the Dynamic routing information and processes.
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var node = DynamicRouteHelper.GetPage();

            var routePair = ResolveRouteValues(node);

            RequestRoutingEventArgs RequestArgs = new RequestRoutingEventArgs()
            {
                Page                  = node,
                Configuration         = routePair,
                CurrentRequestContext = RequestContext
            };

            // Use event to allow users to overwrite the Dynamic Routing Data
            using (var RequestRoutingHandler = DynamicRoutingEvents.RequestRouting.StartEvent(RequestArgs))
            {
                // Setup routing with new values
                RequestArgs.CurrentRequestContext.RouteData.Values["Controller"] = routePair.ControllerName;
                RequestArgs.CurrentRequestContext.RouteData.Values["Action"]     = routePair.ActionName;
                foreach (string Key in routePair.RouteValues.Keys)
                {
                    RequestArgs.CurrentRequestContext.RouteData.Values[Key] = routePair.RouteValues[Key];
                }

                // Allow users to adjust the RequestContext further
                RequestRoutingHandler.FinishEvent();

                // Pass back context
                RequestContext = RequestArgs.CurrentRequestContext;
            }

            IControllerFactory factory    = ControllerBuilder.Current.GetControllerFactory();
            IController        controller = factory.CreateController(RequestContext, routePair.ControllerName);

            controller.Execute(RequestContext);

            factory.ReleaseController(controller);
        }
示例#23
0
            public void ProcessRequestInternal(HttpContextBase httpContext)
            {
                AddVersionHeader(httpContext);
                string             requiredString    = RequestContext.RouteData.GetRequiredString("controller");
                IControllerFactory controllerFactory = ControllerBuilder.Current.GetControllerFactory();
                IController        controller        = controllerFactory.CreateController(RequestContext, requiredString);

                if (controller == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture,
                                                                      "The IControllerFactory '{0}' did not return a controller for a controller named '{1}'.",
                                                                      new object[] { controllerFactory.GetType(), requiredString }));
                }
                try
                {
                    ((ControllerBase)controller).ValidateRequest = _validateRequest;
                    controller.Execute(RequestContext);
                }
                finally
                {
                    controllerFactory.ReleaseController(controller);
                }
            }
        public void ProcessRequest(HttpContext context)
        {
            var                controller         = RequestContext.RouteData.GetRequiredString("controller");
            IController        controllerInstance = null;
            IControllerFactory factory            = null;

            try
            {
                factory            = ControllerBuilder.Current.GetControllerFactory();
                controllerInstance = factory.CreateController(RequestContext, controller);

                var controllerName = RequestContext.RouteData.Values["controller"] as string;
                var actionName     = RequestContext.RouteData.Values["action"] as string;

                context.GetOwinContext().Environment.Add("__App.Metrics.CurrentRouteName__",
                                                         $"{controllerName?.ToLowerInvariant()}/{actionName?.ToLowerInvariant()}");

                controllerInstance?.Execute(RequestContext);
            }
            finally
            {
                factory?.ReleaseController(controllerInstance);
            }
        }
 public void ReleaseController(IController controller)
 {
     factory.ReleaseController(controller);
 }
        /// <summary>
        /// Cleans up the controller by releasing it using the controller factory, and by disposing it.
        /// </summary>
        private static void CleanupController(IController controller, IControllerFactory factory)
        {
            if (controller != null)
                factory.ReleaseController(controller);

            if (controller != null)
                controller.DisposeIfDisposable();
        }
示例#27
0
 internal void ReleaseController()
 {
     Factory.ReleaseController(AsyncController);
 }
示例#28
0
        public void ProcessRequest(HttpContext context)
        {
            var routeValues = RequestContext.RouteData.Values;

            string domainString = Utils.Domain.GetDomain(RequestContext.HttpContext);
            string urlString    = Utils.Domain.GetPath(RequestContext.HttpContext);

            // = context.Request.Url.LocalPath;

            CMS.BL.Entity.tbl_Domains domain = domainService.GetDomainByName(domainString);

#if DEBUG
            if (domain == null && "localhost".Equals(domainString) && RequestContext.HttpContext.Request.IsLocal)
            {
                domain           = domainService.GetDomainByID(SettingsManager.LocalHostDomainID);
                domain.DO_Domain = "localhost";
            }
#endif

            if (domain == null)
            {
                throw new Exception("Custom route handler exception: Can not find domain for url " + urlString);
            }

            if (!domain.DO_CustomRouteHandler)
            {
                RequestContext.RouteData.Values["controller"] = "Website";
                RequestContext.RouteData.Values["action"]     = "Content";
                //default controller/action
            }
            else
            {
                var machingSitemaps = contentService
                                      .GetSitemaps((sitemap) => ("/" + urlString).StartsWith(sitemap.SM_URL) && sitemap.SM_DomainID == domain.DomainID)
                                      .OrderByDescending((sitemap) => sitemap.SM_URL.Length)
                                      .ToList();
                //var machingSitemaps = contentService.GetSitemapByUrl(urlString, domain.DomainID);
                if (machingSitemaps == null || machingSitemaps.Count == 0)
                {
                    RequestContext.RouteData.Values["controller"] = "Website";
                    RequestContext.RouteData.Values["action"]     = "Content";
                    //default controller/action
                }
                else
                {
                    var selectedSitemap = machingSitemaps.First();

                    switch (selectedSitemap.SM_TypeID)
                    {
                    //case (int)SiteMapType.Donation:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    RequestContext.RouteData.Values["action"] = "DonationCategories";
                    //    break;
                    //case (int)SiteMapType.Subscribe:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    RequestContext.RouteData.Values["action"] = "Subscribe";
                    //    RequestContext.RouteData.Values["email"] = context.Request.QueryString["email"]; //extract it
                    //    break;
                    //case (int)SiteMapType.PointsOfInterest:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    RequestContext.RouteData.Values["action"] = "POIs";
                    //    break;
                    //case (int)SiteMapType.Sitemap:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    RequestContext.RouteData.Values["action"] = "Sitemap";
                    //    break;
                    //case (int)SiteMapType.Testimonials:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    RequestContext.RouteData.Values["action"] = "Testimonials";
                    //    break;
                    //case (int)SiteMapType.News:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    if (urlString.Contains(SettingsManager.Blog.SearchUrl.Trim('/')))
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "BlogSearch";
                    //        ExtractRouteValues(domain.DO_Domain, String.Format("{0}/{1}/{2}", "[^/]+", SettingsManager.Blog.SearchUrl.Trim('/'), "{keyword}"));
                    //        break;
                    //    }

                    //    if (urlString.EndsWith("feed"))
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "GetBlogRss";
                    //        break;
                    //    }
                    //    if (string.Compare(selectedSitemap.SM_URL.Trim('/'), urlString, true) == 0)
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "Blog";
                    //        ExtractRouteValues(domain.DO_Domain, String.Format("{0}/{1}/{2}", "{year}", "{month}", "{title}"));
                    //        break;
                    //    }

                    //    if (urlString.Contains(SettingsManager.Blog.CategoryUrl.Trim('/')))
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "BlogCategory";
                    //        ExtractRouteValues(domain.DO_Domain, String.Format("{0}/{1}/{2}", "[^/]+", SettingsManager.Blog.CategoryUrl.Trim('/'), "{name}"));
                    //        break;
                    //    }

                    //    if (urlString.Contains(SettingsManager.Blog.TagUrl.Trim('/')))
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "BlogTag";
                    //        ExtractRouteValues(domain.DO_Domain, String.Format("{0}/{1}/{2}", "[^/]+", SettingsManager.Blog.TagUrl.Trim('/'), "{name}"));
                    //        break;
                    //    }

                    //    RequestContext.RouteData.Values["action"] = "Blog";
                    //    ExtractRouteValues(domain.DO_Domain, String.Format("{0}/{1}/{2}/{3}", selectedSitemap.SM_URL.TrimEnd('/'), "{year}", "{month}", "{title}"));
                    //    break;
                    //case (int)SiteMapType.Gallery:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    if (string.Compare(selectedSitemap.SM_URL.Trim('/'), urlString, true) == 0)
                    //    {
                    //        if (selectedSitemap.SM_ContentTypeID == 1)
                    //        {
                    //            RequestContext.RouteData.Values["action"] = "Gallery";
                    //        }
                    //        else
                    //        {
                    //            RequestContext.RouteData.Values["action"] = "GalleryItem";
                    //            ExtractRouteValues(domain.DO_Domain, "/{*query}");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "GalleryItem";
                    //        ExtractRouteValues(domain.DO_Domain, (selectedSitemap.SM_ContentTypeID == 1 ? selectedSitemap.SM_URL.TrimEnd('/') : "") + "/{*query}");
                    //    }
                    //    break;
                    case (int)SiteMapType.ProductShop:
                        RequestContext.RouteData.Values["controller"] = "Website";
                        if (string.Compare(selectedSitemap.SM_URL.Trim('/'), urlString, true) == 0)
                        {
                            if (selectedSitemap.SM_ContentTypeID == 1)
                            {
                                RequestContext.RouteData.Values["action"] = "ProdCategories";
                            }
                            else
                            {
                                RequestContext.RouteData.Values["action"] = "Products";
                                ExtractRouteValues(domain.DO_Domain, "/{*query}");
                            }
                        }
                        else
                        {
                            RequestContext.RouteData.Values["action"] = "Products";
                            ExtractRouteValues(domain.DO_Domain, (selectedSitemap.SM_ContentTypeID == 1 ? selectedSitemap.SM_URL.TrimEnd('/') : "") + "/{*query}");
                        }
                        break;

                    case (int)SiteMapType.EventShop:
                        RequestContext.RouteData.Values["controller"] = "Website";
                        if (string.Compare(selectedSitemap.SM_URL.Trim('/'), urlString, true) == 0)
                        {
                            if (selectedSitemap.SM_ContentTypeID == 1)
                            {
                                RequestContext.RouteData.Values["action"] = "EventsCategories";
                            }
                            else
                            {
                                RequestContext.RouteData.Values["action"] = "Events";
                                ExtractRouteValues(domain.DO_Domain, "/{*query}");
                            }
                        }
                        else
                        {
                            RequestContext.RouteData.Values["action"] = "Events";
                            ExtractRouteValues(domain.DO_Domain, (selectedSitemap.SM_ContentTypeID == 1 ? selectedSitemap.SM_URL.TrimEnd('/') : "") + "/{*query}");
                        }
                        break;

                    //case (int)SiteMapType.Portfolio:
                    //    RequestContext.RouteData.Values["controller"] = "Website";
                    //    if (string.Compare(selectedSitemap.SM_URL.Trim('/'), urlString, true) == 0)
                    //    {
                    //        if (selectedSitemap.SM_ContentTypeID == 1)
                    //        {
                    //            RequestContext.RouteData.Values["action"] = "Portfolio";
                    //        }
                    //        else
                    //        {
                    //            RequestContext.RouteData.Values["action"] = "PortfolioItem";
                    //            ExtractRouteValues(domain.DO_Domain, "/{*query}");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        RequestContext.RouteData.Values["action"] = "PortfolioItem";
                    //        ExtractRouteValues(domain.DO_Domain, (selectedSitemap.SM_ContentTypeID == 1 ? selectedSitemap.SM_URL.TrimEnd('/') : "") + "/{*query}");
                    //    }
                    //    break;
                    default:
                        RequestContext.RouteData.Values["controller"] = "Website";
                        RequestContext.RouteData.Values["action"]     = "Content";
                        break;
                    }
                }
            }

            string             controllerId = routeValues["Controller"] as string;
            IController        controller   = null;
            IControllerFactory factory      = null;
            try
            {
                factory    = ControllerBuilder.Current.GetControllerFactory();
                controller = factory.CreateController(RequestContext, controllerId);
                if (controller != null)
                {
                    controller.Execute(RequestContext);
                }
                else
                {
                    //Exception logging
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                factory.ReleaseController(controller);
            }
        }
 protected override void ReleaseInstance(object instance)
 {
     _tempData.Save();
     _controllerFactory.ReleaseController(instance);
 }
示例#30
0
 public void ReleaseController(IController controller)
 {
     _innerFactory.ReleaseController(controller);
 }
 protected override void ReleaseInstance(object instance)
 {
     _controllerFactory.ReleaseController(instance);
 }
示例#32
0
        /// <summary>
        /// Provides the object that processes the request.
        /// </summary>
        /// <param name="requestContext">An object that encapsulates information about the request.</param>
        /// <returns>
        /// An object that processes the request.
        /// </returns>
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (requestContext.HttpContext.Request.Url != null && PatternMacher != null && PatternMacher.IsMatch(requestContext.HttpContext.Request.Url.LocalPath))
            {
                return(BaseRouteHandler.GetHttpHandler(requestContext));
            }

            var execute = true;

            var controllerName = requestContext.RouteData.GetRequiredString("controller");
            var actionName     = requestContext.RouteData.GetRequiredString("action");

            IController        controller = null;
            IControllerFactory factory    = null;

            try
            {
                factory    = ControllerBuilder.Current.GetControllerFactory();
                controller = factory.CreateController(requestContext, controllerName);

                if (controller != null)
                {
                    var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
                    var controllerContext    = new ControllerContext(requestContext, (ControllerBase)controller);
                    var actionDescriptor     = controllerDescriptor.FindAction(controllerContext, actionName);

                    var reflectedActionDescriptor = actionDescriptor as ReflectedActionDescriptor;
                    if (reflectedActionDescriptor != null)
                    {
                        var m = reflectedActionDescriptor.MethodInfo;
                        if (m.IsPublic && m.ReturnParameter != null)
                        {
                            var methodOk =
                                typeof(ActionResult).IsAssignableFrom(m.ReturnParameter.ParameterType) ||
                                typeof(Task <ActionResult>).IsAssignableFrom(m.ReturnParameter.ParameterType);

                            if (methodOk)
                            {
                                var allowRouteIfEqualsConfigurationAttributes      = m.GetCustomAttributes(typeof(AllowRouteIfEqualConfigAttribute), true).Cast <AllowRouteIfEqualConfigAttribute>();
                                var allowRouteIfEqualsConfigurationAttributesArray = allowRouteIfEqualsConfigurationAttributes as AllowRouteIfEqualConfigAttribute[] ?? allowRouteIfEqualsConfigurationAttributes.ToArray();

                                execute = allowRouteIfEqualsConfigurationAttributesArray.Length <= 0 || allowRouteIfEqualsConfigurationAttributesArray.Any(allowRouteIfEqualsConfigurationAttribute => allowRouteIfEqualsConfigurationAttribute.IsAllowed());
                            }
                        }
                    }
                }
            }
            // ReSharper disable RedundantCatchClause
            catch (Exception)
            {
                throw;
            }
            // ReSharper restore RedundantCatchClause
            finally
            {
                factory?.ReleaseController(controller);
            }

            if (!execute)
            {
                requestContext.RouteData.Values["controller"] = Controller ?? "Error";
                requestContext.RouteData.Values["action"]     = Action ?? "Index";
            }

            //return BaseRouteHandler.GetHttpHandler(requestContext);
            var httpHandler = BaseRouteHandler.GetHttpHandler(requestContext) as MvcHandler;

            return(httpHandler);
        }