Esempio n. 1
0
        protected ControllerBaseTests(Func <IService <TEntity>, ApiControllerBase <TEntity> > controllerConstructorFunc, Func <TEntity> generateMockObject, List <TEntity> mockObjectList = null)
        {
            _mockService = new Mock <IService <TEntity> >();
            _controller  = controllerConstructorFunc(_mockService.Object);

            _mockObject     = generateMockObject();
            _mockObjectList = mockObjectList ?? Enumerable.Range(0, 5).Select(x => generateMockObject()).ToList();
        }
        public override async Task <Maybe> SetCacheBasedOnContext(ApiControllerBase controller, object value)
        {
            // Use whatever caching mechanism you need to configure a unique identifier
            // from the information in the controller, and save the value of the response.

            //_cache.SetValue(controller.EndpointSetting.EndpointRoute, value);

            return(Maybe.Success());
        }
Esempio n. 3
0
        public static MvcChangePage ChangePage(this ApiControllerBase ac)
        {
            string        data      = ac.Request.Form["Data"];
            JsonObject    jsobj     = JsonObject.Parse(data);
            int           PageIndex = jsobj.GetInt(nameof(PageIndex));
            int           PageSize  = jsobj.GetInt(nameof(PageSize));
            MvcChangePage change    = new MvcChangePage(PageIndex, PageSize, null, Framework.Core.SortType.DESC);

            return(change);
        }
        public override async Task <Maybe <object> > GetCacheBasedOnContext(ApiControllerBase controller)
        {
            // Use whatever caching mechanism you need to determine the unique identifier
            // from the information in the controller, and get the value for the response.

            //var response = _cache.GetValue(controller.EndpointSetting.EndpointRoute);
            //return response.ToMaybe();

            return(Maybe.Empty <object>()); // <-- Represents that no value could be found, so continue as normal
        }
        public static IActionResult JsonResult(this ApiControllerBase self, object data)
        {
            var json = data.ToJson();

            return(new ContentResult
            {
                Content = json,
                ContentType = "application/json",
                StatusCode = 200
            });
        }
Esempio n. 6
0
        private void SetUserContextInController(ApiControllerBase controller, ActionExecutingContext context)
        {
            string cookieValue = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault();

            controller.UserSession = ((ISessionFactory)context.HttpContext.RequestServices.GetService(typeof(ISessionFactory))).GetActiveSessionModel(cookieValue);

            var sessionContext = (ISessionContext)context.HttpContext.RequestServices.GetService(typeof(ISessionContext));

            sessionContext.UserSession = controller.UserSession;
            sessionContext.SessionId   = cookieValue;
        }
Esempio n. 7
0
        private void FillActionAttribute(object actionArgument, ApiControllerBase controller)
        {
            if (actionArgument == null)
            {
                return;
            }


            foreach (var item in actionArgument.GetType().GetProperties()
                     .Where(x => !x.PropertyType.IsValueType && !x.PropertyType.IsPrimitive && !x.PropertyType.FullName.StartsWith("System.")).ToArray())
            {
                FillActionAttribute(item.GetValue(actionArgument), controller);
            }
        }
Esempio n. 8
0
        protected override async Task <Maybe> ClientValidates(ApiControllerBase controller)
        {
            // Just as a Resource Owner has a Token to validate who they are; a Client, such as
            // another MicroService in the same Ecosystem, has its own token called a secretKey.
            // This can be a short-cached item controlled by the ISettingService implementation.
            // It can be controlled and changed daily, weekly, monthly, or more in the database,
            // and the systems should still be able to talk to each other (after the cache switchover).

            var serviceSetting = await _setting.GetServiceSetting(null); // <-- Current static implementation returns "secretKey"

            if (serviceSetting.Value.SecretKey == controller.SecretKey)
            {
                return(Maybe.Success());
            }
            return(Maybe.Failure());
        }
Esempio n. 9
0
        protected override async Task <Maybe <JinnAuthClaim> > ValidateResourceOwner(ApiControllerBase controller)
        {
            // Your Bearer Token and other values are in the headers and other properties of the controller ^^^
            // You can use this information on each request to check if the request has a valid Resource Owner
            // Return the appropriate claims and password expiration date.

            if (string.IsNullOrWhiteSpace(controller.AccessToken))
            {
                return(Maybe.Empty <JinnAuthClaim>());
            }

            return(new JinnAuthClaim(
                       new List <Claim> {
                new Claim(ClaimTypes.Name, "Test Username")
                , new Claim("ResourceOwnerID", "1")
            },
                       DateTime.UtcNow.AddHours(1)
                       ).ToMaybe());
        }
Esempio n. 10
0
        public async Task <PostedDoc> GetDocBytesFromRequest(ApiControllerBase controller)
        {
            PostedDoc doc = new PostedDoc {
                DocBytes = null
            };
            var provider = new MultipartMemoryStreamProvider();

            await controller.Request.Content.ReadAsMultipartAsync(provider);

            if (provider.Contents.Count > 0)
            {
                var    file = provider.Contents[0];
                string name = file.Headers.ContentDisposition.FileName?.Trim('\"');
                doc.DocBytes = await file.ReadAsByteArrayAsync();

                doc.FileName = name;
            }
            return(doc);
        }
Esempio n. 11
0
        private void SetMethodType(ActionExecutingContext actionContext, ApiControllerBase controller)
        {
            var method = actionContext.HttpContext.Request.Method.ToLower();

            switch (method)
            {
            case HttpMethodType.Get:
                controller.SetResponseModel(HttpMethodType.Get);
                break;

            case HttpMethodType.Delete:
                controller.SetResponseModel(HttpMethodType.Delete);
                break;

            case HttpMethodType.Post:
                controller.SetPostResponseModel(HttpMethodType.Post);
                break;

            case HttpMethodType.Put:
                controller.SetPostResponseModel(HttpMethodType.Put);
                break;
            }
        }
        public async Task Deve_Buscar_Registro_Por_Id_Pela_Controller()
        {
            //Given
            var services = new ServiceCollection();
            var entity   = new TestEntity(
                new NomeValueObject("Weslley_1", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );
            var entity2 = new TestEntity(
                new NomeValueObject("Weslley_2", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );
            var entity3 = new TestEntity(
                new NomeValueObject("Weslley_3", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );

            var searchDto = new TestSearchDto();

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddDomainNotifications();
            services.AddContext <Context>(options =>
            {
                options
                .EnabledInMemory()
                .EnabledLogging();
            });
            services.AddRepository <ITestReadRepository, TestReadRepository>("Optsol.Components.Test.Utils");
            services.AddApplications <IBaseServiceApplication <TestEntity>, TestServiceApplication>("Optsol.Components.Test.Utils");
            services.AddServices();

            var provider = services.BuildServiceProvider();
            IApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel, TestSearchDto> controllerBase =
                new ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel, TestSearchDto>(
                    provider.GetRequiredService <ILoggerFactory>(),
                    provider.GetRequiredService <IBaseServiceApplication <TestEntity> >(),
                    provider.GetRequiredService <IResponseFactory>());

            var unitOfWork = provider.GetRequiredService <IUnitOfWork>();
            var repository = provider.GetRequiredService <ITestWriteRepository>();

            await repository.InsertAsync(entity);

            await repository.InsertAsync(entity2);

            await repository.InsertAsync(entity3);

            await unitOfWork.CommitAsync();

            //When
            var actionResult = await controllerBase.GetByIdAsync(entity.Id);

            //Then
            ((OkObjectResult)actionResult).StatusCode.Should().NotBeNull();
            ((OkObjectResult)actionResult).StatusCode.Should().Be((int)HttpStatusCode.OK);

            var resultObj = JsonConvert.DeserializeObject <Response <TestViewModel> >(((OkObjectResult)actionResult).Value.ToJson());

            resultObj.Should().NotBeNull();
            resultObj.Success.Should().BeTrue();
            resultObj.Failure.Should().BeFalse();
            resultObj.Messages.Should().BeEmpty();
            resultObj.Data.Should().NotBeNull();
            resultObj.Data.Nome.Should().Be(entity.Nome.ToString());
            resultObj.Data.Contato.Should().Be(entity.Email.ToString());
            resultObj.Data.Ativo.Should().Be("Inativo");
        }
        public async Task Deve_Remover_Registro_Pelo_Id_Pelo_Servico()
        {
            //Given
            InsertTestViewModel model = new InsertTestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddDomainNotifications();
            services.AddContext <Context>(options =>
            {
                options
                .EnabledInMemory()
                .EnabledLogging();
            });
            services.AddApplications <ITestServiceApplication, TestServiceApplication>("Optsol.Components.Test.Utils");
            services.AddServices();

            var provider = services.BuildServiceProvider();
            ITestServiceApplication serviceApplication = provider.GetRequiredService <ITestServiceApplication>();
            IApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel, TestSearchDto> controllerBase =
                new ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel, TestSearchDto>(
                    provider.GetRequiredService <ILoggerFactory>(),
                    provider.GetRequiredService <IBaseServiceApplication <TestEntity> >(),
                    provider.GetRequiredService <IResponseFactory>());

            await serviceApplication.InsertAsync <InsertTestViewModel, InsertTestViewModel>(model);

            var entity = (await serviceApplication.GetAllAsync <TestViewModel>()).FirstOrDefault();

            //When
            var actionResult = await controllerBase.DeleteAsync(entity.Id);

            //Then
            ((OkObjectResult)actionResult).StatusCode.Should().NotBeNull();
            ((OkObjectResult)actionResult).StatusCode.Should().Be((int)HttpStatusCode.OK);

            var resultObj = JsonConvert.DeserializeObject <Response>(((OkObjectResult)actionResult).Value.ToJson());

            resultObj.Should().NotBeNull();
            resultObj.Success.Should().BeTrue();
            resultObj.Failure.Should().BeFalse();
            resultObj.Messages.Should().BeEmpty();

            (await serviceApplication.GetAllAsync <TestViewModel>()).Should().BeEmpty();
        }
Esempio n. 14
0
 public static IEnumerable <T> Respond <T>(this SearchResults <T> searchResults, ApiControllerBase controller) where T : class
 {
     return(controller.HandleSearchResults(searchResults));
 }
        public async Task Deve_Buscar_Todos_Pela_Controller()
        {
            //Given
            var services = new ServiceCollection();
            var entity   = new TestEntity(
                new NomeValueObject("Weslley_1", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );
            var entity2 = new TestEntity(
                new NomeValueObject("Weslley_2", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );
            var entity3 = new TestEntity(
                new NomeValueObject("Weslley_3", "Carneiro"),
                new EmailValueObject("*****@*****.**")
                );

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddContext <TestContext>(new ContextOptionsBuilder());
            services.AddRepository <ITestReadRepository, TestReadRepository>("Optsol.Components.Test.Utils");
            services.AddApplicationServices <ITestServiceApplication, TestServiceApplication>("Optsol.Components.Test.Utils");
            services.AddAServices();

            var provider = services.BuildServiceProvider();
            IApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> controllerBase =
                new ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel>(
                    provider.GetRequiredService <ILogger <ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> > >(),
                    provider.GetRequiredService <IBaseServiceApplication <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> >(),
                    provider.GetRequiredService <IResponseFactory>());

            var unitOfWork = provider.GetRequiredService <IUnitOfWork>();
            var repository = provider.GetRequiredService <ITestWriteRepository>();

            await repository.InsertAsync(entity);

            await repository.InsertAsync(entity2);

            await repository.InsertAsync(entity3);

            await unitOfWork.CommitAsync();

            //When
            var actionResult = await controllerBase.GetAllAsync();

            //Then
            ((OkObjectResult)actionResult).StatusCode.Should().NotBeNull();
            ((OkObjectResult)actionResult).StatusCode.Should().Be((int)HttpStatusCode.OK);

            var resultObj = JsonConvert.DeserializeObject <ResponseList <TestViewModel> >(((OkObjectResult)actionResult).Value.ToJson());

            resultObj.Should().NotBeNull();
            resultObj.Success.Should().BeTrue();
            resultObj.Failure.Should().BeFalse();
            resultObj.Messages.Should().BeEmpty();
            resultObj.DataList.Should().NotBeNull();
            resultObj.DataList.All(a => a.Valid).Should().BeTrue();
            resultObj.DataList.All(a => a.Invalid).Should().BeFalse();
            resultObj.DataList.SelectMany(s => s.Notifications).Should().BeEmpty();
            resultObj.DataList.Should().HaveCount(3);
            resultObj.DataList.Any(a => a.Id == entity.Id).Should().BeTrue();
            resultObj.DataList.Any(a => a.Contato == entity2.Email.ToString()).Should().BeTrue();
            resultObj.DataList.Any(a => a.Nome == entity3.Nome.ToString()).Should().BeTrue();
        }
        public async Task Deve_Atualizar_Registro_Pelo_Servico()
        {
            //Given
            InsertTestViewModel model = new InsertTestViewModel();

            model.Nome    = "Weslley Carneiro";
            model.Contato = "*****@*****.**";

            var services = new ServiceCollection();

            services.AddLogging();
            services.AddAutoMapper(typeof(TestViewModel));
            services.AddContext <TestContext>(new ContextOptionsBuilder());
            services.AddApplicationServices <ITestServiceApplication, TestServiceApplication>("Optsol.Components.Test.Utils");
            services.AddAServices();

            var provider = services.BuildServiceProvider();
            ITestServiceApplication serviceApplication = provider.GetRequiredService <ITestServiceApplication>();
            IApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> controllerBase =
                new ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel>(
                    provider.GetRequiredService <ILogger <ApiControllerBase <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> > >(),
                    provider.GetRequiredService <IBaseServiceApplication <TestEntity, TestViewModel, TestViewModel, InsertTestViewModel, UpdateTestViewModel> >(),
                    provider.GetRequiredService <IResponseFactory>());

            await serviceApplication.InsertAsync(model);

            var data        = (await serviceApplication.GetAllAsync()).DataList.Single();
            var updateModel = new UpdateTestViewModel();

            updateModel.Id      = data.Id;
            updateModel.Nome    = $"Weslley Alterado";
            updateModel.Contato = model.Contato;

            //When
            var actionResult = await controllerBase.UpdateAsync(updateModel);

            //Then
            ((OkObjectResult)actionResult).StatusCode.Should().NotBeNull();
            ((OkObjectResult)actionResult).StatusCode.Should().Be((int)HttpStatusCode.OK);

            var resultObj = JsonConvert.DeserializeObject <Response>(((OkObjectResult)actionResult).Value.ToJson());

            resultObj.Should().NotBeNull();
            resultObj.Success.Should().BeTrue();
            resultObj.Failure.Should().BeFalse();
            resultObj.Messages.Should().BeEmpty();

            var resultService = await serviceApplication.GetByIdAsync(updateModel.Id);

            resultService.Data.Should().NotBeNull();
            resultService.Data.Id.Should().NotBeEmpty();
            resultService.Data.Nome.Should().Be(updateModel.Nome);
            resultService.Data.Contato.Should().Be(updateModel.Contato);
            resultService.Data.Ativo.Should().Be("Inativo");
        }
        /// <summary>
        /// Processes the action.
        /// </summary>
        /// <param name="controller">The API controller that initiated this action.</param>
        /// <param name="pageGuid">The page unique identifier.</param>
        /// <param name="blockGuid">The block unique identifier.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        internal static IHttpActionResult ProcessAction(ApiControllerBase controller, Guid?pageGuid, Guid?blockGuid, string actionName, JToken parameters)
        {
            try
            {
                BlockCache blockCache = null;
                PageCache  pageCache  = null;

                //
                // Find the block.
                //
                if (blockGuid.HasValue)
                {
                    blockCache = BlockCache.Get(blockGuid.Value);
                }

                if (blockCache == null)
                {
                    return(new NotFoundResult(controller));
                }

                // Find the page.
                if (pageGuid.HasValue)
                {
                    pageCache = PageCache.Get(pageGuid.Value);
                }
                else
                {
                    // This can be removed once the obsolete API endpoints
                    // that allowed for sending an action to a block identifier
                    // without a page identifier are removed.
                    pageCache = blockCache.Page;
                }

                if (blockCache == null || pageCache == null)
                {
                    return(new NotFoundResult(controller));
                }

                //
                // Get the authenticated person and make sure it's cached.
                //
                var person = GetPerson(controller, null);
                HttpContext.Current.AddOrReplaceItem("CurrentPerson", person);

                //
                // Ensure the user has access to both the page and block.
                //
                if (!pageCache.IsAuthorized(Security.Authorization.VIEW, person) || !blockCache.IsAuthorized(Security.Authorization.VIEW, person))
                {
                    return(new StatusCodeResult(HttpStatusCode.Unauthorized, controller));
                }

                //
                // Get the class that handles the logic for the block.
                //
                var blockCompiledType = blockCache.BlockType.GetCompiledType();
                var block             = Activator.CreateInstance(blockCompiledType);

                if (!(block is Blocks.IRockBlockType rockBlock))
                {
                    return(new NotFoundResult(controller));
                }

                var requestContext = controller.RockRequestContext;

                //
                // Set the basic block parameters.
                //
                rockBlock.BlockCache     = blockCache;
                rockBlock.PageCache      = pageCache;
                rockBlock.RequestContext = requestContext;

                var actionParameters = new Dictionary <string, JToken>(StringComparer.InvariantCultureIgnoreCase);

                //
                // Parse any posted parameter data.
                //
                if (parameters != null)
                {
                    try
                    {
                        foreach (var kvp in parameters.ToObject <Dictionary <string, JToken> >())
                        {
                            if (kvp.Key == "__context")
                            {
                                // If we are given any page parameters then
                                // override the query string parameters. This
                                // is what allows mobile and obsidian blocks to
                                // pass in the original page parameters.
                                if (kvp.Value["pageParameters"] != null)
                                {
                                    var pageParameters = kvp.Value["pageParameters"].ToObject <Dictionary <string, string> >();

                                    rockBlock.RequestContext.SetPageParameters(pageParameters);
                                }
                            }
                            else
                            {
                                actionParameters.AddOrReplace(kvp.Key, kvp.Value);
                            }
                        }
                    }
                    catch
                    {
                        return(new BadRequestErrorMessageResult("Invalid parameter data.", controller));
                    }
                }

                //
                // Parse any query string parameter data.
                //
                foreach (var q in controller.Request.GetQueryNameValuePairs())
                {
                    actionParameters.AddOrReplace(q.Key, JToken.FromObject(q.Value.ToString()));
                }

                requestContext.AddContextEntitiesForPage(pageCache);

                return(InvokeAction(controller, rockBlock, actionName, actionParameters, parameters));
            }
            catch (Exception ex)
            {
                return(new BadRequestErrorMessageResult(ex.Message, controller));
            }
        }
        /// <summary>
        /// Processes the specified block action.
        /// </summary>
        /// <param name="controller">The API controller that initiated this action.</param>
        /// <param name="block">The block.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="actionParameters">The action parameters.</param>
        /// <param name="bodyParameters">The posted body parameters.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">actionName
        /// or
        /// actionData</exception>
        internal static IHttpActionResult InvokeAction(ApiControllerBase controller, Blocks.IRockBlockType block, string actionName, Dictionary <string, JToken> actionParameters, JToken bodyParameters)
        {
            // Parse the body content into our normal parameters.
            if (bodyParameters != null)
            {
                try
                {
                    // Parse any posted parameter data, existing query string
                    // parameters take precedence.
                    foreach (var kvp in bodyParameters.ToObject <Dictionary <string, JToken> >())
                    {
                        actionParameters.AddOrIgnore(kvp.Key, kvp.Value);
                    }
                }
                catch
                {
                    return(new BadRequestErrorMessageResult("Invalid parameter data.", controller));
                }
            }

            //
            // Find the action they requested. First search by name
            // and then further filter by any method constraint attributes.
            //
            var actions = block.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public)
                          .Where(m => m.GetCustomAttribute <Blocks.BlockActionAttribute>()?.ActionName == actionName)
                          .ToList();

            if (actions.Count == 0)
            {
                return(new NotFoundResult(controller));
            }

            var action = FindBestActionForParameters(actions, actionParameters);

            if (action == null)
            {
                // This is an actual configuration error, so throw an error.
                throw new AmbiguousMatchException("The request matched multiple actions.");
            }

            var methodParameters = action.GetParameters();
            var parameters       = new List <object>();

            //
            // Go through each parameter and convert it to the proper type.
            //
            for (int i = 0; i < methodParameters.Length; i++)
            {
                // Check if this parameter is requesting it's content from the body.
                if (methodParameters[i].GetCustomAttribute <FromBodyAttribute>() != null)
                {
                    if (bodyParameters != null)
                    {
                        parameters.Add(bodyParameters.ToObject(methodParameters[i].ParameterType));
                    }
                    else if (methodParameters[i].IsOptional)
                    {
                        parameters.Add(Type.Missing);
                    }
                    else
                    {
                        return(new BadRequestErrorMessageResult($"Parameter '{methodParameters[i].Name}' is required.", controller));
                    }

                    continue;
                }

                var key = actionParameters.Keys.SingleOrDefault(k => k.ToLowerInvariant() == methodParameters[i].Name.ToLower());

                if (key != null)
                {
                    try
                    {
                        //
                        // If the target type is nullable and the action parameter is an empty
                        // string then consider it null. A GET query cannot have null values.
                        //
                        if (Nullable.GetUnderlyingType(methodParameters[i].ParameterType) != null)
                        {
                            if (actionParameters[key].Type == JTokenType.String && actionParameters[key].ToString() == string.Empty)
                            {
                                parameters.Add(null);

                                continue;
                            }
                        }

                        parameters.Add(actionParameters[key].ToObject(methodParameters[i].ParameterType));
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);

                        return(new BadRequestErrorMessageResult($"Parameter type mismatch for '{methodParameters[i].Name}'.", controller));
                    }
                }
                else if (methodParameters[i].IsOptional)
                {
                    parameters.Add(Type.Missing);
                }
                else
                {
                    return(new BadRequestErrorMessageResult($"Parameter '{methodParameters[i].Name}' is required.", controller));
                }
            }

            object result;

            try
            {
                result = action.Invoke(block, parameters.ToArray());
            }
            catch (TargetInvocationException ex)
            {
                ExceptionLogService.LogApiException(ex.InnerException, controller.Request, GetPerson(controller, null)?.PrimaryAlias);
                result = new BlockActionResult(HttpStatusCode.InternalServerError, GetMessageForClient(ex));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogApiException(ex, controller.Request, GetPerson(controller, null)?.PrimaryAlias);
                result = new BlockActionResult(HttpStatusCode.InternalServerError, GetMessageForClient(ex));
            }

            //
            // Handle the result type.
            //
            if (result is IHttpActionResult httpActionResult)
            {
                return(httpActionResult);
            }
            else if (result is BlockActionResult actionResult)
            {
                var isErrorStatusCode = ( int )actionResult.StatusCode >= 400;

                if (isErrorStatusCode && actionResult.Content is string)
                {
                    return(new NegotiatedContentResult <HttpError>(actionResult.StatusCode, new HttpError(actionResult.Content.ToString()), controller));
                }
                else if (actionResult.Error != null)
                {
                    return(new NegotiatedContentResult <HttpError>(actionResult.StatusCode, new HttpError(actionResult.Error), controller));
                }
                else if (actionResult.Content is HttpContent httpContent)
                {
                    var response = controller.Request.CreateResponse(actionResult.StatusCode);
                    response.Content = httpContent;
                    return(new ResponseMessageResult(response));
                }
                else if (actionResult.ContentClrType != null)
                {
                    var genericType = typeof(System.Web.Http.Results.NegotiatedContentResult <>).MakeGenericType(actionResult.ContentClrType);
                    return(( IHttpActionResult )Activator.CreateInstance(genericType, actionResult.StatusCode, actionResult.Content, controller));
                }
                else
                {
                    return(new StatusCodeResult(actionResult.StatusCode, controller));
                }
            }
            else if (action.ReturnType == typeof(void))
            {
                return(new OkResult(controller));
            }
            else
            {
                return(new OkNegotiatedContentResult <object>(result, controller));
            }
        }
Esempio n. 19
0
 public DailyGoalHelper(ApiControllerBase controllerBase)
 {
     _controllerBase = controllerBase;
 }
Esempio n. 20
0
 protected override bool HostOriginRefererChecks(ApiControllerBase controller)
 {
     // Here, you can check headers and other information in the controller object, and
     // decide if you want to allow the sender access.
     return(true);
 }
        public static IActionResult ApiResult <TData>(this ApiControllerBase self, IRequest request, TData data)
        {
            var result = new Response <TData>(request, data);

            return(self.JsonResult(result));
        }
        public static IActionResult ApiFailResult(this ApiControllerBase self, IRequest request)
        {
            var result = new EmptyRespone(request, isSuccessful: false);

            return(self.JsonResult(result));
        }
 public static IActionResult ApiListResult <TItem>(this ApiControllerBase self, IRequest request, IEnumerable <TItem> items)
 {
     return(self.ApiResult(request, new GenericListResult <TItem>(items)));
 }