public override IHttpController CreateController(HttpRequestMessage request)
        {
            IHttpController controller = null;

            _traceWriter.TraceBeginEnd(
                request,
                TraceCategories.ControllersCategory,
                TraceLevel.Info,
                _innerDescriptor.GetType().Name,
                CreateControllerMethodName,
                beginTrace: null,
                execute: () =>
            {
                controller = _innerDescriptor.CreateController(request);
            },
                endTrace: (tr) =>
            {
                tr.Message = controller == null
                                        ? SRResources.TraceNoneObjectMessage
                                        : HttpControllerTracer.ActualControllerType(controller).FullName;
            },
                errorTrace: null);

            if (controller != null && !(controller is HttpControllerTracer))
            {
                return(new HttpControllerTracer(request, controller, _traceWriter));
            }

            return(controller);
        }
 private void InitalizeController(HttpRequestMessage requestContext, IHttpController controller)
 {
     var controllerInitializer = controller as IStardustController;
     if (!controllerInitializer.IsInstance() || !controllerInitializer.DoInitializationOnActionInvocation)
         return;
     Initialize(requestContext.RequestUri, requestContext.Method.Method, controllerInitializer);
 }
        /// <summary>Initializes a new instance of the <see cref="HttpControllerContext"/> class.</summary>
        /// <param name="requestContext">The request context.</param>
        /// <param name="request">The HTTP request.</param>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <param name="controller">The controller.</param>
        public HttpControllerContext(HttpRequestContext requestContext, HttpRequestMessage request,
                                     HttpControllerDescriptor controllerDescriptor, IHttpController controller)
        {
            if (requestContext == null)
            {
                throw Error.ArgumentNull("requestContext");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (controllerDescriptor == null)
            {
                throw Error.ArgumentNull("controllerDescriptor");
            }

            if (controller == null)
            {
                throw Error.ArgumentNull("controller");
            }

            _requestContext       = requestContext;
            _request              = request;
            _controllerDescriptor = controllerDescriptor;
            _controller           = controller;
        }
Example #4
0
        IHttpController IHttpControllerActivator.Create(HttpControllerContext controllerContext, Type controllerType)
        {
            IHttpController controller = null;

            _traceWriter.TraceBeginEnd(
                controllerContext.Request,
                TraceCategories.ControllersCategory,
                TraceLevel.Info,
                _innerActivator.GetType().Name,
                CreateMethodName,
                beginTrace: null,
                execute: () =>
            {
                controller = _innerActivator.Create(controllerContext, controllerType);
            },
                endTrace: (tr) =>
            {
                tr.Message = controller == null ? SRResources.TraceNoneObjectMessage : controller.GetType().FullName;
            },
                errorTrace: null);

            if (controller != null && !(controller is HttpControllerTracer))
            {
                controller = new HttpControllerTracer(controller, _traceWriter);
            }

            return(controller);
        }
        public void Create_Invokes_Inner_And_Traces()
        {
            // Arrange
            Mock <ApiController>            mockController = new Mock <ApiController>();
            Mock <IHttpControllerActivator> mockActivator  = new Mock <IHttpControllerActivator>()
            {
                CallBase = true
            };

            mockActivator.Setup(b => b.Create(It.IsAny <HttpRequestMessage>(), It.IsAny <HttpControllerDescriptor>(), It.IsAny <Type>())).Returns(mockController.Object);
            HttpRequestMessage            request     = new HttpRequestMessage();
            TestTraceWriter               traceWriter = new TestTraceWriter();
            HttpControllerActivatorTracer tracer      = new HttpControllerActivatorTracer(mockActivator.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "Create"
                },
                new TraceRecord(request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "Create"
                }
            };

            // Act
            IHttpController createdController = ((IHttpControllerActivator)tracer).Create(request, controllerDescriptor: null, controllerType: mockController.Object.GetType());

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.IsAssignableFrom <HttpControllerTracer>(createdController);
        }
        public void Create_UsesControllerFromRequestLevelDependencyScope()
        {
            // Arrange
            var controller = new ControllerWithCtorParams(42);
            var mockScope  = new Mock <IDependencyScope>();

            mockScope
            .Setup(r => r.GetService(typeof(ControllerWithCtorParams)))
            .Returns(controller)
            .Verifiable();
            var config  = new HttpConfiguration();
            var request = new HttpRequestMessage();

            request.SetConfiguration(config);
            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;
            var descriptor = new HttpControllerDescriptor(
                config,
                "Name",
                typeof(ControllerWithCtorParams)
                );
            var activator = new DefaultHttpControllerActivator();

            // Act
            IHttpController result = activator.Create(
                request,
                descriptor,
                typeof(ControllerWithCtorParams)
                );

            // Assert
            Assert.Same(controller, result);
            mockScope.Verify();
        }
        public void Create_MakesInstanceOfController()
        {
            // Arrange
            var config  = new HttpConfiguration();
            var request = new HttpRequestMessage();

            request.SetConfiguration(config);
            var descriptor = new HttpControllerDescriptor(
                config,
                "Simple",
                typeof(SimpleController)
                );
            var activator = new DefaultHttpControllerActivator();

            // Act
            IHttpController result = activator.Create(
                request,
                descriptor,
                typeof(SimpleController)
                );

            // Assert
            Assert.NotNull(result);
            Assert.IsType <SimpleController>(result);
        }
        /// <summary>Initializes a new instance of the <see cref="HttpControllerContext"/> class.</summary>
        /// <param name="requestContext">The request context.</param>
        /// <param name="request">The HTTP request.</param>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <param name="controller">The controller.</param>
        public HttpControllerContext(HttpRequestContext requestContext, HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor, IHttpController controller)
        {
            if (requestContext == null)
            {
                throw Error.ArgumentNull("requestContext");
            }

            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (controllerDescriptor == null)
            {
                throw Error.ArgumentNull("controllerDescriptor");
            }

            if (controller == null)
            {
                throw Error.ArgumentNull("controller");
            }

            _requestContext = requestContext;
            _request = request;
            _controllerDescriptor = controllerDescriptor;
            _controller = controller;
        }
Example #9
0
        public void CreateController_Invokes_Inner_And_Traces()
        {
            // Arrange
            Mock <HttpControllerDescriptor> mockControllerDescriptor = CreateMockControllerDescriptor();

            mockControllerDescriptor.Setup(b => b.CreateController(It.IsAny <HttpRequestMessage>())).Returns(_controller);
            TestTraceWriter traceWriter           = new TestTraceWriter();
            HttpControllerDescriptorTracer tracer = GetHttpControllerDescriptorTracer(mockControllerDescriptor.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "CreateController"
                },
                new TraceRecord(_request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "CreateController"
                }
            };

            // Act
            IHttpController controller = tracer.CreateController(_request);

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.IsAssignableFrom <HttpControllerTracer>(controller);
        }
        public void CreateController_Invokes_Inner_And_Traces()
        {
            // Arrange
            Mock <ApiController>          mockController = new Mock <ApiController>();
            Mock <IHttpControllerFactory> mockFactory    = new Mock <IHttpControllerFactory>()
            {
                CallBase = true
            };

            mockFactory.Setup(b => b.CreateController(It.IsAny <HttpControllerContext>(), It.IsAny <string>())).Returns(mockController.Object);
            HttpControllerContext       controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());
            TestTraceWriter             traceWriter       = new TestTraceWriter();
            HttpControllerFactoryTracer tracer            = new HttpControllerFactoryTracer(mockFactory.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(controllerContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "CreateController"
                },
                new TraceRecord(controllerContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End, Operation = "CreateController"
                }
            };

            // Act
            IHttpController createdController = ((IHttpControllerFactory)tracer).CreateController(controllerContext, "anyName");

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.IsAssignableFrom <HttpControllerTracer>(createdController);
        }
        public void Create_DoesnotCacheControllerFromRequestLevelDependencyScope()
        {
            // Arrange
            int count      = 0;
            var controller = new ControllerWithCtorParams(42);
            var mockScope  = new Mock <IDependencyScope>();

            mockScope.Setup(r => r.GetService(typeof(ControllerWithCtorParams))).Returns(() =>
            {
                count++;
                return(new ControllerWithCtorParams(42));
            }).Verifiable();
            var config  = new HttpConfiguration();
            var request = new HttpRequestMessage();

            request.SetConfiguration(config);
            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;
            var descriptor = new HttpControllerDescriptor(config, "Name", typeof(ControllerWithCtorParams));
            var activator  = new DefaultHttpControllerActivator();

            // Act
            IHttpController result1 = activator.Create(request, descriptor, typeof(ControllerWithCtorParams));
            IHttpController result2 = activator.Create(request, descriptor, typeof(ControllerWithCtorParams));

            // Assert
            Assert.NotEqual(result1, result2);
            mockScope.Verify();
            Assert.Equal(2, count);
        }
        public void Create_MixupInstanceCreationAndDependencyScope()
        {
            // Arrange
            var controller = new ControllerWithCtorParams(42);
            var mockScope  = new Mock <IDependencyScope>();

            mockScope.Setup(r => r.GetService(typeof(ControllerWithCtorParams))).Returns(controller).Verifiable();
            var config  = new HttpConfiguration();
            var request = new HttpRequestMessage();

            request.SetConfiguration(config);
            request.Properties[HttpPropertyKeys.DependencyScope] = mockScope.Object;
            var descriptorControllerWithCtorParamsResult = new HttpControllerDescriptor(config, "Name", typeof(ControllerWithCtorParams));
            var descriptorSimpleController = new HttpControllerDescriptor(config, "Simple", typeof(SimpleController));
            var activator = new DefaultHttpControllerActivator();

            // Act
            IHttpController simpleController = activator.Create(request, descriptorSimpleController, typeof(SimpleController));
            IHttpController controllerWithCtorParamsResult = activator.Create(request, descriptorControllerWithCtorParamsResult, typeof(ControllerWithCtorParams));

            // Assert
            Assert.NotNull(simpleController);
            Assert.IsType <SimpleController>(simpleController);
            Assert.Same(controller, controllerWithCtorParamsResult);
            mockScope.Verify();
        }
Example #13
0
        public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            HttpActionDescriptor decriptor = null;

            try
            {
                decriptor = base.SelectAction(controllerContext);
            }
            catch (HttpResponseException ex)
            {
                var code = ex.Response.StatusCode;
                if (code != HttpStatusCode.NotFound && code != HttpStatusCode.MethodNotAllowed)
                {
                    throw;
                }
                var routeData = controllerContext.RouteData;
                routeData.Values["action"] = DefaultActionName;
                IHttpController httpController = ControllerBuilder();
                controllerContext.Controller           = httpController;
                controllerContext.ControllerDescriptor =
                    new HttpControllerDescriptor(controllerContext.Configuration,
                                                 httpController.GetType().Name, httpController.GetType());
                decriptor = base.SelectAction(controllerContext);
            }
            return(decriptor);
        }
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            try
            {
                if (actionExecutedContext.Exception != null)
                {
                    string controllerWarning = string.Empty;
                    var    actionDesc        = ((ReflectedHttpActionDescriptor)actionExecutedContext.ActionContext.ActionDescriptor);
                    var    requestHeader     = actionExecutedContext.ActionContext.Request.Headers;


                    IHttpController controller         = actionExecutedContext.ActionContext.ControllerContext.Controller;
                    string          apiMethodArguments = JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments);

                    string consolidatedErrorMessage = string.Format("Controller: {0};\nAction: {1};\nParams: {2};\nTrace: {3}",
                                                                    actionDesc.ControllerDescriptor.ControllerName, actionDesc.ActionName, apiMethodArguments,
                                                                    actionExecutedContext.Exception.StackTrace);

                    Exception ex = new Exception(consolidatedErrorMessage, actionExecutedContext.Exception);
                    Exception innerMostException = GetInnerMostException(actionExecutedContext.Exception);



                    actionExecutedContext.Response = GetResponseDataForUI(actionExecutedContext.Exception, requestHeader);
                }
            }
            catch (Exception)
            {
                actionExecutedContext.Response = GetResponseDataForUI(actionExecutedContext.Exception, actionExecutedContext.ActionContext.Request.Headers);
            }
        }
            /// <inheritdoc />
            /// <summary>
            /// Executes an action.
            /// </summary>
            /// <param name="controllerContext">Controller context.</param>
            /// <param name="cancellationToken">Cancellation token.</param>
            /// <returns>Response message.</returns>
            public Task <HttpResponseMessage> ExecuteAsync(
                HttpControllerContext controllerContext,
                CancellationToken cancellationToken)
            {
                if (_controller == null)
                {
                    var request = controllerContext.Request;

                    if (request
                        .GetDependencyScope()
                        .GetService(typeof(IUnityContainer)) is IUnityContainer container)
                    {
                        container.RegisterInstance(controllerContext);
                        container.RegisterInstance(request);
                        container.RegisterInstance(cancellationToken);

                        UnityTypesRegistrator.RegisterTypes(container);
                    }

                    _controller = Activator.Create(
                        request,
                        controllerContext.ControllerDescriptor,
                        ControllerType);
                }

                controllerContext.Controller = _controller;

                return(_controller.ExecuteAsync(controllerContext, cancellationToken));
            }
        private static HttpActionDescriptor SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)
        {
            request.SetRouteData(routeData);

            routeData.RemoveOptionalRoutingParameters();

            HttpControllerDescriptor controllerDescriptor = config.Services.GetHttpControllerSelector().SelectController(request);

            // Get the per-controller configuration
            config = controllerDescriptor.Configuration;
            request.SetConfiguration(config);
            HttpRequestContext requestContext = request.GetRequestContext();

            if (requestContext == null)
            {
                requestContext = new HttpRequestContext
                {
                    Configuration   = config,
                    RouteData       = routeData,
                    Url             = new UrlHelper(request),
                    VirtualPathRoot = config.VirtualPathRoot
                };
            }

            IHttpController controller = controllerDescriptor.CreateController(request);

            using (controller as IDisposable)
            {
                HttpControllerContext controllerContext = new HttpControllerContext(requestContext, request, controllerDescriptor, controller);
                return(config.Services.GetActionSelector().SelectAction(controllerContext));
            }
        }
        /// <summary> Create IHttpController. </summary>
        /// <param name="request"> </param>
        /// <param name="controllerDescriptor"> </param>
        /// <param name="controllerType"> </param>
        /// <returns> </returns>
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            IHttpController controller = (IHttpController)container.Resolve(controllerType);

            request.RegisterForDispose(new Release(() => container.Release(controller)));

            return(controller);
        }
Example #18
0
        private IHttpController ResolveAndReleaseControllerUsingSelfHostDependencyResolver()
        {
            IHttpController result = null;

            result = (IHttpController)facility.DependencyResolver.GetService(typeof(AspNetWebApiFacilityWebHostTestCase.WebApiController));
            facility.DependencyResolver.Dispose();
            return(result);
        }
 /// <summary>
 /// Disposes of a controller if possible
 /// </summary>
 /// <param name="controller">The controller to dispose</param>
 public void ReleaseController(IHttpController controller)
 {
     var disposable = controller as IDisposable;
     if (disposable != null)
     {
         disposable.Dispose();
     }
 }
        /// <summary>
        /// Creates the <see cref="IHttpController"/> specified by <paramref name="controllerType"/> using the given <paramref name="request"/>
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <param name="controllerDescriptor">The controller descriptor</param>
        /// <returns>An instance of type <paramref name="controllerType"/>.</returns>
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (controllerDescriptor == null)
            {
                throw Error.ArgumentNull("controllerDescriptor");
            }

            if (controllerType == null)
            {
                throw Error.ArgumentNull("controllerType");
            }

            try
            {
                // First check in the local fast cache and if not a match then look in the broader
                // HttpControllerDescriptor.Properties cache
                if (_fastCache == null)
                {
                    // If dependency resolver returns controller object then keep asking it whenever we need a new instance
                    IHttpController instance = (IHttpController)request.GetDependencyScope().GetService(controllerType);
                    if (instance != null)
                    {
                        return(instance);
                    }

                    // Otherwise create a delegate for creating a new instance of the type
                    Func <IHttpController> activator = TypeActivator.Create <IHttpController>(controllerType);
                    Tuple <HttpControllerDescriptor, Func <IHttpController> > cacheItem = Tuple.Create(controllerDescriptor, activator);
                    Interlocked.CompareExchange(ref _fastCache, cacheItem, null);

                    // Execute the delegate
                    return(activator());
                }
                else if (_fastCache.Item1 == controllerDescriptor)
                {
                    // If the key matches and we already have the delegate for creating an instance then just execute it
                    return(_fastCache.Item2());
                }
                else
                {
                    // If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for
                    // that HttpControllerDescriptor instance
                    Func <IHttpController> activator = (Func <IHttpController>)controllerDescriptor.Properties.GetOrAdd(
                        _cacheKey,
                        key => TypeActivator.Create <IHttpController>(controllerType));
                    return(activator());
                }
            }
            catch (Exception ex)
            {
                throw Error.InvalidOperation(ex, SRResources.DefaultControllerFactory_ErrorCreatingController, controllerType.Name);
            }
        }
        /// <summary>
        /// Creates the <see cref="IHttpController"/> specified by <paramref name="controllerType"/> using the given <paramref name="request"/>
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <param name="controllerDescriptor">The controller descriptor</param>
        /// <returns>An instance of type <paramref name="controllerType"/>.</returns>
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            try
            {
                Func <IHttpController> activator;

                // First check in the local fast cache and if not a match then look in the broader
                // HttpControllerDescriptor.Properties cache
                if (_fastCache == null)
                {
                    IHttpController controller = GetInstanceOrActivator(request, controllerType, out activator);
                    if (controller != null)
                    {
                        // we have a controller registered with the dependency resolver for this controller type
                        return(controller);
                    }
                    else
                    {
                        Tuple <HttpControllerDescriptor, Func <IHttpController> > cacheItem = Tuple.Create(controllerDescriptor, activator);
                        Interlocked.CompareExchange(ref _fastCache, cacheItem, null);
                    }
                }
                else if (_fastCache.Item1 == controllerDescriptor)
                {
                    // If the key matches and we already have the delegate for creating an instance.
                    activator = _fastCache.Item2;
                }
                else
                {
                    // If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for
                    // that HttpControllerDescriptor instance
                    object value;
                    if (controllerDescriptor.Properties.TryGetValue(_cacheKey, out value))
                    {
                        activator = (Func <IHttpController>)value;
                    }
                    else
                    {
                        IHttpController controller = GetInstanceOrActivator(request, controllerType, out activator);
                        if (controller != null)
                        {
                            // we have a controller registered with the dependency resolver for this controller type
                            return(controller);
                        }
                        else
                        {
                            controllerDescriptor.Properties.TryAdd(_cacheKey, activator);
                        }
                    }
                }

                return(activator());
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #22
0
        private static HttpControllerDescriptor BuildHttpControllerDescriptor(IHttpController controller, string controllerName = "AnyController", HttpConfiguration httpConfiguration = null)
        {
            HttpControllerDescriptor expectedInner = new Mock <HttpControllerDescriptor>().Object;

            expectedInner.ControllerName = controllerName;
            expectedInner.ControllerType = controller.GetType();
            expectedInner.Configuration  = httpConfiguration ?? new HttpConfiguration();
            return(expectedInner);
        }
Example #23
0
        internal async Task <HttpResponseMessage> SendFluentApiAsync(HttpRequestMessage request, CancellationToken cancellationToken, HttpControllerDescriptor controllerDescriptor)
        {
            ExceptionDispatchInfo exceptionInfo;
            HttpControllerContext controllerContext = null;

            try
            {
                IHttpController controller = controllerDescriptor.CreateController(request);
                if (controller == null)
                {
                    var httpError = new HttpError(string.Format(CultureInfo.CurrentCulture, "No HTTP resource was found that matches the request URI '{0}'.", request.RequestUri));
                    if (request.ShouldIncludeErrorDetail())
                    {
                        httpError.Add(HttpErrorKeys.MessageDetailKey, "No controller was created to handle this request.");
                    }

                    return(request.CreateErrorResponse(HttpStatusCode.NotFound, httpError));
                }

                controllerContext = CreateControllerContext(request, controllerDescriptor, controller);
                return(await controller.ExecuteAsync(controllerContext, cancellationToken));
            }
            catch (OperationCanceledException)
            {
                // Propogate the canceled task without calling exception loggers or handlers.
                throw;
            }
            catch (HttpResponseException httpResponseException)
            {
                return(httpResponseException.Response);
            }
            catch (Exception exception)
            {
                exceptionInfo = ExceptionDispatchInfo.Capture(exception);
            }

            Debug.Assert(exceptionInfo.SourceException != null);

            ExceptionContext exceptionContext = new ExceptionContext(
                exceptionInfo.SourceException,
                ExceptionCatchBlocks.HttpControllerDispatcher,
                request)
            {
                ControllerContext = controllerContext,
            };

            await ExceptionLogger.LogAsync(exceptionContext, cancellationToken);

            HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext, cancellationToken);

            if (response == null)
            {
                exceptionInfo.Throw();
            }

            return(response);
        }
Example #24
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            HttpActionContext     actionContext     = actionExecutedContext.ActionContext;
            HttpControllerContext controllerContext = actionContext.ControllerContext;
            Exception             oldException      = actionExecutedContext.Exception;

            // Get the name of the action ("Decrypt") and controller ("DocumentController")
            string actionName = actionContext.ActionDescriptor.ActionName;

            ServiceException sameException = oldException as ServiceException;

            if (sameException != null)
            {
                // Add the action name.
                sameException.Action = actionName;

                try
                {
                    // Get the value from the attribute on the method.
                    IHttpController controller            = controllerContext.Controller;
                    var             serviceErrorAttribute = (ServiceErrorAttribute)controller.GetType().GetMethod(actionName).GetCustomAttribute(typeof(ServiceErrorAttribute), false);

                    // Get additional properties
                    sameException.ConsumeAttribute(serviceErrorAttribute);
                }
                catch { }

                actionExecutedContext.Exception = sameException;
            }
            else
            {
                string userSafeMessage = null;
                try
                {
                    // Check the method for an attribute we can use for more information.

                    // Get the value from the attribute on the method.
                    IHttpController controller            = controllerContext.Controller;
                    var             serviceErrorAttribute = (ServiceErrorAttribute)controller.GetType().GetMethod(actionName).GetCustomAttribute(typeof(ServiceErrorAttribute), false);
                    userSafeMessage = serviceErrorAttribute.Message;

                    ServiceException newException = new ServiceException(userSafeMessage, actionExecutedContext.Exception);
                    newException.Action = actionName;

                    // Get additional properties
                    newException.ConsumeAttribute(serviceErrorAttribute);
                    actionExecutedContext.Exception = newException;
                }
                catch
                {
                    userSafeMessage = "An error occurred. Please contact an administrator.";
                    ServiceException newException = new ServiceException(userSafeMessage, actionExecutedContext.Exception);
                    newException.Action             = actionName;
                    actionExecutedContext.Exception = newException;
                }
            }
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <param name="controllerDescriptor">
        /// The controller descriptor.
        /// </param>
        /// <param name="controllerType">
        /// The controller type.
        /// </param>
        /// <returns>
        /// The <see cref="IHttpController"/>.
        /// </returns>
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            this.logger.Debug(() => $"Create controller {controllerType.FullName}");
            var             type           = request.GetDependencyScope().GetService(controllerType) as IHttpController;
            IHttpController httpController = (IHttpController)type;

            this.logger.Debug(() => $"Controller created {controllerType.FullName}");
            return(httpController);
        }
        public HttpControllerTracer(HttpRequestMessage request, IHttpController innerController, ITraceWriter traceWriter)
        {
            Contract.Assert(innerController != null);
            Contract.Assert(traceWriter != null);

            _innerController = innerController;
            _request = request;
            _traceWriter = traceWriter;
        }
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            IHttpController instance =
                ControllersHelper.IsUmbracoController(controllerType)
                  ? this._defaultHttpControllerActivator.Create(request, controllerDescriptor, controllerType)
                  : StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IHttpController;

            return(instance);
        }
Example #28
0
        public HttpControllerTracer(HttpRequestMessage request, IHttpController innerController, ITraceWriter traceWriter)
        {
            Contract.Assert(innerController != null);
            Contract.Assert(traceWriter != null);

            _innerController = innerController;
            _request         = request;
            _traceWriter     = traceWriter;
        }
 public ControllerCreatedEvent(object source,
                               HttpRequestMessage request,
                               HttpControllerDescriptor descriptor,
                               IHttpController controller) : base(source)
 {
     this.Request = request;
     this.ControllerDescriptor = descriptor;
     this.Controller           = controller;
 }
Example #30
0
        private void InitalizeController(HttpRequestMessage requestContext, IHttpController controller)
        {
            var controllerInitializer = controller as IStardustController;

            if (!controllerInitializer.IsInstance() || !controllerInitializer.DoInitializationOnActionInvocation)
            {
                return;
            }
            Initialize(requestContext.RequestUri, requestContext.Method.Method, controllerInitializer);
        }
Example #31
0
        public IHttpController Create(
            HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {
            IHttpController controller = _internalActivator.Create(request, controllerDescriptor, controllerType);

            _container.SatisfyImportsOnce(controller); // MEF injection
            return(controller);
        }
        private Task <HttpResponseMessage> SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            if (_disposed)
            {
                throw Error.ObjectDisposed(SRResources.HttpMessageHandlerDisposed, typeof(HttpControllerDispatcher).Name);
            }

            // Lookup route data, or if not found as a request property then we look it up in the route table
            IHttpRouteData routeData;

            if (!request.Properties.TryGetValue(HttpPropertyKeys.HttpRouteDataKey, out routeData))
            {
                routeData = _configuration.Routes.GetRouteData(request);
                if (routeData != null)
                {
                    request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
                }
                else
                {
                    // TODO, 328927, add an error message in the response body
                    return(TaskHelpers.FromResult(request.CreateResponse(HttpStatusCode.NotFound)));
                }
            }

            RemoveOptionalRoutingParameters(routeData.Values);

            HttpControllerDescriptor httpControllerDescriptor = ControllerSelector.SelectController(request);

            if (httpControllerDescriptor == null)
            {
                // TODO, 328927, add an error message in the response body
                return(TaskHelpers.FromResult(request.CreateResponse(HttpStatusCode.NotFound)));
            }

            IHttpController httpController = httpControllerDescriptor.CreateController(request);

            if (httpController == null)
            {
                // TODO, 328927, add an error message in the response body
                return(TaskHelpers.FromResult(request.CreateResponse(HttpStatusCode.NotFound)));
            }

            // Create context
            HttpControllerContext controllerContext = new HttpControllerContext(_configuration, routeData, request);

            controllerContext.Controller           = httpController;
            controllerContext.ControllerDescriptor = httpControllerDescriptor;

            return(httpController.ExecuteAsync(controllerContext, cancellationToken));
        }
Example #33
0
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            IHttpController result = null;

            if (controllerType != null)
            {
                result = _container.Resolve(controllerType) as IHttpController;
            }

            return(result);
        }
Example #34
0
        public void ReleaseController(IHttpController controller)
        {
            var disposableController = controller as IDisposable;

            if (disposableController != null)
            {
                disposableController.Dispose();
            }

            _windsorContainer.Release(controller);
        }
Example #35
0
        public static HttpControllerContext CreateControllerContext(IHttpController instance, string controllerName, Type controllerType, HttpConfiguration configuration = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            context.Controller = instance;
            context.ControllerDescriptor = CreateControllerDescriptor(controllerName, controllerType, config);

            return context;
        }
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            if (instance != null)
            {
                context.Controller = instance;
            }

            return context;
        }
Example #37
0
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.SetConfiguration(config);
            req.SetRouteData(route);

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            if (instance != null)
            {
                context.Controller = instance;
            }
            context.ControllerDescriptor = CreateControllerDescriptor(config);

            return context;
        }
 public override void ReleaseController(IHttpController controller, HttpControllerContext controllerContext)
 {
     _traceWriter.TraceBeginEnd(
         controllerContext.Request,
         TraceCategories.ControllersCategory,
         TraceLevel.Info,
         _innerDescriptor.GetType().Name,
         ReleaseControllerMethodName,
         beginTrace: (tr) =>
         {
             tr.Message = HttpControllerTracer.ActualControllerType(controller).FullName;
         },
         execute: () =>
         {
             IHttpController actualController = HttpControllerTracer.ActualController(controller);
             _innerDescriptor.ReleaseController(actualController, controllerContext);
         },
         endTrace: null,
         errorTrace: null);
 }
 void IHttpControllerFactory.ReleaseController(HttpControllerContext controllerContext, IHttpController controller)
 {
     _traceWriter.TraceBeginEnd(
         controllerContext.Request,
         TraceCategories.ControllersCategory,
         TraceLevel.Info,
         _innerFactory.GetType().Name,
         ReleaseControllerMethodName,
         beginTrace: (tr) =>
         {
             tr.Message = HttpControllerTracer.ActualControllerType(controller).FullName;
         },
         execute: () =>
         {
             IHttpController actualController = HttpControllerTracer.ActualController(controller);
             _innerFactory.ReleaseController(controllerContext, actualController);
         },
         endTrace: null,
         errorTrace: null);
 }
 public HttpControllerTracer(HttpRequestMessage request, IHttpController innerController, ITraceWriter traceWriter)
 {
     _innerController = innerController;
     _request = request;
     _traceWriter = traceWriter;
 }
 private static HttpControllerDescriptor BuildHttpControllerDescriptor(IHttpController controller, string controllerName = "AnyController", HttpConfiguration httpConfiguration = null)
 {
     HttpControllerDescriptor expectedInner = new Mock<HttpControllerDescriptor>().Object;
     expectedInner.ControllerName = controllerName;
     expectedInner.ControllerType = controller.GetType();
     expectedInner.Configuration = httpConfiguration ?? new HttpConfiguration();
     return expectedInner;
 }
 private void RegisterController(string path, IHttpController httpController)
 {
     httpController.Init(Server.Instance.properties);
     routes.Add(RouteBuilder.RouteToRegex(path), httpController);
 }
 public void ReleaseController(HttpControllerContext controllerContext, IHttpController controller)
 {
     throw new NotImplementedException();
 }
 public HttpControllerTracer(IHttpController innerController, ITraceWriter traceWriter)
 {
     _innerController = innerController;
     _traceWriter = traceWriter;
 }
        private static HttpControllerContext CreateControllerContext(
            HttpRequestMessage request, 
            HttpControllerDescriptor controllerDescriptor,
            IHttpController controller)
        {
            Contract.Assert(request != null);
            Contract.Assert(controllerDescriptor != null);
            Contract.Assert(controller != null);

            HttpConfiguration controllerConfiguration = controllerDescriptor.Configuration;

            // Set the controller configuration on the request properties
            HttpConfiguration requestConfig = request.GetConfiguration();
            if (requestConfig == null)
            {
                request.SetConfiguration(controllerConfiguration);
            }
            else
            {
                if (requestConfig != controllerConfiguration)
                {
                    request.SetConfiguration(controllerConfiguration);
                }
            }

            HttpRequestContext requestContext = request.GetRequestContext();

            // if the host doesn't create the context we will fallback to creating it.
            if (requestContext == null)
            {
                requestContext = new RequestBackedHttpRequestContext(request)
                {
                    // we are caching controller configuration to support per controller configuration.
                    Configuration = controllerConfiguration,
                };

                // if the host did not set a request context we will also set it back to the request.
                request.SetRequestContext(requestContext);
            }

            return new HttpControllerContext(requestContext, request, controllerDescriptor, controller);
        }
 public void ReleaseController(IHttpController controller)
 {
     _innerFactory.ReleaseController(controller);
 }
 public void ReleaseController(IHttpController controller)
 {
     this._kernel.ReleaseComponent(controller);
 }
 /// <summary>
 /// Gets logger.
 /// </summary>
 /// <param name="controller">
 /// The controller.
 /// </param>
 /// <returns>
 /// The <see cref="Logger"/>.
 /// </returns>
 private static Logger GetLogger(IHttpController controller)
 {
     return LogManager.GetLogger(controller.GetType().FullName);
 }
 public static IHttpController ActualController(IHttpController controller)
 {
     HttpControllerTracer tracer = controller as HttpControllerTracer;
     return tracer == null ? controller : tracer._innerController;
 }
 public static Type ActualControllerType(IHttpController controller)
 {
     return ActualController(controller).GetType();
 }
 public virtual void ReleaseController(HttpControllerContext controllerContext, IHttpController controller)
 {
     IDisposable disposable = controller as IDisposable;
     if (disposable != null)
     {
         disposable.Dispose();
     }
 }