private static bool ParseBody <TCommunicatorRequest>(ControllerBase controllerBase,
                                                             out TCommunicatorRequest request,
                                                             out IActionResult actionResult) where TCommunicatorRequest : class, ICommunicatorRequest
        {
            try
            {
                request = JsonConvert.DeserializeObject <TCommunicatorRequest>(
                    new StreamReader(controllerBase.Request.Body).ReadToEndAsync().Result);
            }
            catch (JsonException)
            {
                request = default;

                {
                    actionResult = controllerBase.BadRequest("Given request can't be parsed correctly");
                    return(false);
                }
            }

            if (request == null)
            {
                actionResult = controllerBase.BadRequest("Given request can't be parsed correctly");
                return(false);
            }

            actionResult = null;
            return(true);
        }
Пример #2
0
        /// <summary>
        /// This is used to return the ServiceGetResultCode for the
        /// associated ServiceGetResult.ResultCode.
        /// </summary>
        /// <typeparam name="T">This is the ServiceGetResult type</typeparam>
        /// <typeparam name="U">This is the response object that is held by this</typeparam>
        /// <param name="result">This is ServiceResultCode corresponding to the
        /// result code</param>
        /// <param name="controllerBase">The Web API controller</param>
        /// <returns>This is the IActionResult that corresponds to the result code</returns>
        public static IActionResult ToApiGetResponse <T, U>(this T result, ControllerBase controllerBase)
            where T : ServiceGetResult <U>
            where U : class
        {
            IActionResult response = null;

            switch (result.ResultCode)
            {
            case ServiceGetResultCode.Success:
                response = controllerBase.Ok(result.Resource);
                break;

            case ServiceGetResultCode.NotFound:
                response = controllerBase.NotFound();
                break;

            case ServiceGetResultCode.ValidationErrors:
                response = controllerBase.BadRequest(result.ValidationErrors);
                break;

            case ServiceGetResultCode.NotAuthorized:
                response = controllerBase.Unauthorized();
                break;

            default:
                response = controllerBase.BadRequest("Unknown error occurred");
                break;
            }

            return(response);
        }
        public static IActionResult getErrors(ControllerBase c, Exception ex)
        {
            if (ex.GetType() == typeof(DbUpdateException))
            {
                if (ex.InnerException is SqlException sqlException)
                {
                    switch (sqlException.Number)
                    {
                    case 2627: return(c.BadRequest(new { errors = new { UniqueConstraint = sqlException.Message } }));                     // Unique constraint error

                    case 547: return(c.BadRequest(new { errors = new { constraintViolation = sqlException.Message } }));                   // Constraint check violation

                    case 2601: return(c.BadRequest(new { errors = new { duplicatedkey = "Cannot insert duplicate key row in object" } })); // Duplicated key row error

                    // Constraint violation exception
                    // A custom exception of yours for concurrency issues

                    default:
                        return(c.StatusCode(500, new { errors = new { unhandleException = sqlException.Message } }));
                        // A custom exception of yours for other DB issues
                    }
                }
            }
            return(c.StatusCode(500, new { errors = new { unhandleException = ex.Message } }));
        }
Пример #4
0
        /// <summary>
        /// Creates an ActionResult from a service Result
        /// </summary>
        /// <returns>The action result.</returns>
        /// <param name="result">Service Result.</param>
        /// <typeparam name="T">The data type of the Result.</typeparam>
        public static ActionResult FromResult <T>(this ControllerBase controller, Result <T> result)
        {
            switch (result.ResultType)
            {
            case ResultType.Ok:
                if (result.Data == null)
                {
                    return(controller.NoContent());
                }
                else
                {
                    return(controller.Ok(result.Data));
                }

            case ResultType.NotFound:
                return(controller.NotFound(result.Errors));

            case ResultType.Invalid:
                return(controller.BadRequest(result.Errors));

            case ResultType.Unexpected:
                return(controller.BadRequest(result.Errors));

            case ResultType.Unauthorized:
                return(controller.Unauthorized());

            default:
                throw new Exception("An unhandled result has occurred as a result of a service call.");
            }
        }
Пример #5
0
        public async Task <IActionResult> DeleteItem(ControllerBase controller,
                                                     IDbResourceRepository <T, O> repo, int id)
        {
            try
            {
                string desc = GetControllerDescription(controller);
                _logger.LogInfo(desc);
                if (id < 1)
                {
                    _logger.LogWarn($"{desc}: Empty request submitted");
                    return(controller.BadRequest());
                }
                var user = await _userService.GetCurrentUser();

                if (user == null)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted - Not a valid user");
                    return(controller.BadRequest());
                }
                var exists = await repo.Exists(id, user?.Id);

                if (!exists)
                {
                    _logger.LogWarn($"{desc}: Item with id {id} was not found or does not belong to {user?.Email}");
                    return(controller.NotFound());
                }
                if (!controller.ModelState.IsValid)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted");
                    return(controller.BadRequest(controller.ModelState));
                }



                var item = await repo.GetById(id,
                                              new BaseQueryOptions()
                {
                    UserId = user != null ? user.Id : ""
                });

                if (item == null)
                {
                    _logger.LogWarn($"{desc}: Item with id {id} was not found or does not belong to {user?.Email}");
                    return(controller.NotFound());
                }

                var isSuccess = await repo.Delete(item);

                if (!isSuccess)
                {
                    return(InternalError(controller, "{desc}: Item delete failed"));
                }
                _logger.LogInfo($"{desc}: Item deleted");
                return(controller.Ok(id));
            }
            catch (Exception e)
            {
                return(InternalError(controller, e));
            }
        }
        public async Task <IActionResult> Create <D>(ControllerBase controller,
                                                     IDbResourceRepository <T> repo, D itemDTO)
        {
            string desc = GetControllerDescription(controller);

            try
            {
                _logger.LogInfo(desc);
                if (itemDTO == null)
                {
                    _logger.LogWarn($"{desc}: Empty request submitted");
                    return(controller.BadRequest());
                }
                if (!controller.ModelState.IsValid)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted");
                    return(controller.BadRequest(controller.ModelState));
                }
                var item = _mapper.Map <T>(itemDTO);

                var isSuccess = await repo.Create(item);

                if (!isSuccess)
                {
                    return(InternalError(controller, $"{desc}: Item creation failed"));
                }
                _logger.LogInfo($"{desc}: Item created");
                return(controller.Created("", new { item }));
            }
            catch (Exception e)
            {
                return(InternalError(controller, e));
            }
        }
Пример #7
0
        public async Task <IActionResult> UpdateItem <D>(ControllerBase controller,
                                                         IDbResourceRepository <T, O> repo, int id, D itemDTO)
        {
            try
            {
                string desc = GetControllerDescription(controller);
                _logger.LogInfo(desc);
                if (id < 1 || itemDTO == null)
                {
                    _logger.LogWarn($"{desc}: Empty request submitted");
                    return(controller.BadRequest());
                }
                var user = await _userService.GetCurrentUser();

                if (user == null)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted - Not a valid user");
                    return(controller.BadRequest());
                }
                var exists = await repo.Exists(id, user?.Id);

                if (!exists)
                {
                    _logger.LogWarn($"{desc}: Item with id {id} was not found or does not belong to {user?.Email}");
                    return(controller.NotFound());
                }
                if (!controller.ModelState.IsValid)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted");
                    return(controller.BadRequest(controller.ModelState));
                }


                // map data to DTO
                var item = _mapper.Map <T>(itemDTO);
                // force item.Id to be id passed in and userId to currently authenticated user
                item.Id = id;

                // set the userId to the currently authenticated user
                item.UserId = user?.Id;

                var isSuccess = await repo.Update(item);

                if (!isSuccess)
                {
                    return(InternalError(controller, $"{desc}: Update failed"));
                }
                _logger.LogInfo($"{desc}: Update Successful");

                item.UserId = null;

                return(controller.Ok(new { item }));
            }
            catch (Exception e)
            {
                return(InternalError(controller, $"Server Error: {e.Message} - {e.InnerException}"));
            }
        }
        /// <summary>
        /// Adds an error to model state and returns the whole model state as
        /// BadRequest result.
        /// </summary>
        /// <param name="controller">Instance of the
        /// <see cref="ControllerBase"/>.</param>
        /// <param name="fieldName">Field name causing the problem.</param>
        /// <param name="errorMessage">Error message describing the problem.
        /// </param>
        /// <returns>Instance of <see cref="IActionResult"/></returns>
        public static IActionResult BadRequest(
            this ControllerBase controller,
            string fieldName,
            string errorMessage)
        {
            if (controller.ModelState
                .TryAddModelError(fieldName, errorMessage))
            {
                return(controller.BadRequest(controller.ModelState));
            }

            return(controller.BadRequest(errorMessage));
        }
Пример #9
0
 /// <summary>
 /// Extend try catch
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="ctrl"></param>
 /// <param name="func"></param>
 /// <returns></returns>
 public static ActionResult <T> TryCatchWithModelState <T>(this ControllerBase ctrl, Func <T> func)
 {
     if (!ctrl.ModelState.IsValid)
     {
         return(ctrl.BadRequest(ctrl.ModelState));
     }
     try
     {
         return(ctrl.Ok(func()));
     }
     catch (Exception ex)
     {
         return(ctrl.BadRequest(ex.Message));
     }
 }
Пример #10
0
 public static BadRequestObjectResult BadRequestWithErrors(this ControllerBase controller)
 {
     return(controller.BadRequest(
                controller.ModelState.Values
                .SelectMany(e => e.Errors)
                .Select(e => e.ErrorMessage)));
 }
Пример #11
0
        public static ActionResult ToActionResult(this ControllerBase controllerBase, IResult result)
        {
            switch (result.Status)
            {
            case ResultStatus.Ok:
                return(controllerBase.Ok(new
                {
                    success = true,
                    data = result.GetValue()
                }));

            case ResultStatus.NotFound:
                return(controllerBase.NotFound());

            case ResultStatus.Invalid:
                return(controllerBase.BadRequest(new
                {
                    success = false,
                    errors = result.ValidationErrors
                }));

            case ResultStatus.Error:
                return(controllerBase.StatusCode(500));

            default: throw new NotSupportedException($"Result {result.Status} translation is not supported");
            }
        }
        public async Task <IActionResult> Delete(ControllerBase controller,
                                                 IDbResourceRepository <T> repo, int id)
        {
            try
            {
                string desc = GetControllerDescription(controller);
                _logger.LogInfo(desc);
                if (id < 1)
                {
                    _logger.LogWarn($"{desc}: Empty request submitted");
                    return(controller.BadRequest());
                }
                var item = await repo.FindById(id);

                if (item == null)
                {
                    _logger.LogWarn($"{desc}: Item with id ${id} was not found");
                    return(controller.NotFound());
                }

                var isSuccess = await repo.Delete(item);

                if (!isSuccess)
                {
                    return(InternalError(controller, "{desc}: Item delete failed"));
                }
                _logger.LogInfo("{desc}: Item deleted");
                return(controller.Ok(id));
            }
            catch (Exception e)
            {
                return(InternalError(controller, e));
            }
        }
Пример #13
0
        /// <summary>
        /// This is used to return the ServiceCreateResultCode for the
        /// associated ServiceCreateResult.ResultCode.
        /// </summary>
        /// <typeparam name="T">This is the ServiceCreateResult type</typeparam>
        /// <typeparam name="U">This is the response object that is held by this</typeparam>
        /// <param name="result">This is ServiceResultCode corresponding to the
        /// result code</param>
        /// <param name="controllerBase">The Web API controller</param>
        /// <returns>This is the IActionResult that corresponds to the result code</returns>
        public static IActionResult ToApiCreateResponse <T, U>(this T result, ControllerBase controllerBase)
            where T : ServiceCreateResult <U>
            where U : class
        {
            IActionResult response;

            switch (result.ResultCode)
            {
            case ServiceCreateResultCode.Success:
                response = controllerBase.Created(string.Empty, result.Identifier);
                break;

            case ServiceCreateResultCode.ResourceAlreadyExists:
                response = controllerBase.StatusCode((int)HttpStatusCode.PreconditionFailed, result.Identifier);
                break;

            case ServiceCreateResultCode.ValidationErrors:
                response = controllerBase.BadRequest(result.ValidationErrors);
                break;

            default:
                throw new InvalidCastException($"Unexpected {typeof(T).Name} value of {result.ResultCode} received.");
            }

            return(response);
        }
Пример #14
0
        /// <summary>
        /// This is used to retrieve the response for a service change result.
        /// </summary>
        /// <typeparam name="T">This is the service result type</typeparam>
        /// <param name="result">This is the result</param>
        /// <param name="controllerBase">Controller base</param>
        /// <returns>The corresponding action</returns>
        public static IActionResult ToApiChangeResponse <T>(this T result, ControllerBase controllerBase)
            where T : ServiceChangeResult
        {
            IActionResult response;

            switch (result.ResultCode)
            {
            case ServiceChangeResultCode.Success:
                response = controllerBase.NoContent();
                break;

            case ServiceChangeResultCode.NotFound:
                response = controllerBase.NotFound();
                break;

            case ServiceChangeResultCode.ValidationErrors:
                response = controllerBase.BadRequest(result.ValidationErrors);
                break;

            case ServiceChangeResultCode.VersionConflict:
                response = controllerBase.Conflict();
                break;

            default:
                throw new InvalidCastException($"Unexpected {typeof(T).Name} value of {result.ResultCode} received.");
            }

            return(response);
        }
Пример #15
0
        /// <summary>
        /// Get Item by Id
        /// </summary>
        /// <typeparam name="D">Data Transfer Object class</typeparam>
        /// <param name="controller"></param>
        /// <param name="repo"></param>
        /// <param name="id"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <IActionResult> GetItem <D>(ControllerBase controller,
                                                      IDbResourceRepository <T, O> repo, int id, IBaseQueryOptions options)
        {
            try
            {
                string desc = GetControllerDescription(controller);
                _logger.LogInfo($"{desc}: {id}");

                // set options.UserId for the current authenticated user
                var user = await _userService.GetCurrentUser();

                if (user == null)
                {
                    _logger.LogWarn($"{desc}: Invalid request submitted - Not a valid user");
                    return(controller.BadRequest());
                }
                options.UserId = user?.Id;

                var item = await repo.GetById(id, options);

                if (item == null)
                {
                    _logger.LogWarn($"{desc}: Item {id} was not found or does not belong to {user?.Email} ");
                    return(controller.NotFound());
                }
                var response = _mapper.Map <D>(item);
                _logger.LogInfo($"{desc} - Successful");
                return(controller.Ok(response));
            }
            catch (Exception e)
            {
                return(InternalError(controller, $"Server Error: {e.Message} - {e.InnerException}"));
            }
        }
        public static async Task <IActionResult> BulkDeleteAsync(this ControllerBase controller, IDeletableMembershipBoundedService service, string membershipId, string[] ids)
        {
            var utilizer = controller.GetUtilizer();

            if (ids != null)
            {
                var isDeleted = await service.BulkDeleteAsync(utilizer, membershipId, ids);

                if (isDeleted != null)
                {
                    if (isDeleted.Value)
                    {
                        return(controller.NoContent());
                    }
                    else
                    {
                        return(controller.BulkDeleteFailed(ids));
                    }
                }
                else
                {
                    return(controller.BulkDeletePartial());
                }
            }
            else
            {
                return(controller.BadRequest());
            }
        }
        public static ActionResult FromServiceOperationResult(
            this ControllerBase controllerBase, ServiceOperationResult result
            )
        {
            switch (result.StatusCode)
            {
            case HttpStatusCode.OK:
                return(controllerBase.Ok());

            case HttpStatusCode.Accepted:
                return(controllerBase.Accepted());

            case HttpStatusCode.Unauthorized:
                return(controllerBase.Unauthorized());

            case HttpStatusCode.NotFound:
                return(controllerBase.NotFound(result.Errors));

            case HttpStatusCode.Conflict:
                return(controllerBase.Conflict(result.Errors));

            case HttpStatusCode.UnprocessableEntity:
                return(controllerBase.UnprocessableEntity(result.Errors));

            case HttpStatusCode.NotImplemented:
                return(controllerBase.StatusCode((int)result.StatusCode, result.Errors));

            default:
                return(controllerBase.BadRequest(result.Errors));
            }
        }
Пример #18
0
 public static BadRequestObjectResult Error(this ControllerBase controller, string message)
 {
     return(controller.BadRequest(new
     {
         Message = message
     }));
 }
Пример #19
0
        public static IActionResult GetActionResultFromServiceResult(this ControllerBase controller, ServiceResult result)
        {
            switch (result.StatusCode)
            {
            case StatusCodes.Status200OK:
            {
                return(controller.Ok(result.ContentResult));
            }

            case StatusCodes.Status201Created:
            {
                return(controller.StatusCode(StatusCodes.Status201Created, result.ContentResult));
            }

            case StatusCodes.Status400BadRequest:
            {
                return(controller.BadRequest(result.ContentResult));
            }

            case StatusCodes.Status404NotFound:
            {
                return(controller.NotFound(result.ContentResult));
            }

            case StatusCodes.Status500InternalServerError:
            {
                return(controller.StatusCode(StatusCodes.Status500InternalServerError, result.ContentResult));
            }

            default:
            {
                return(controller.StatusCode(result.StatusCode, "Unhandled Status Code"));
            }
            }
        }
Пример #20
0
        public static IActionResult CreateResponse <T>(this ControllerBase controller, HttpStatusCode statusCode,
                                                       SwaggerResponse <T> result)
        {
            switch (statusCode)
            {
            case HttpStatusCode.OK:
                return(controller.Ok(result.Result));

            case HttpStatusCode.Created:
                if (result.Result is Ronny createRonny)
                {
                    return(controller.Created(new Uri($"{controller.BasePath()}/ronnies/{createRonny.Id}"), createRonny));
                }
                else
                {
                    return(controller.Created("", result.Result));
                }

            case HttpStatusCode.Accepted:
                if (result.Result is Ronny updateRonny)
                {
                    return(controller.Accepted(new Uri($"{controller.BasePath()}/ronnies/{updateRonny.Id}"), updateRonny));
                }
                else
                {
                    return(controller.Accepted("", result.Result));
                }

            case HttpStatusCode.BadRequest:
                return(controller.BadRequest(result.Error));

            default:
                return(controller.StatusCode((int)statusCode));
            }
        }
        public static IActionResult ValidationError(this ControllerBase controller, ValidationException validationException)
        {
            controller.Response.Headers.Add(DtoHelper.PayloadTypeHeaderName, DtoHelper.ValidationErrorPayloadType);
            var error = WebApiHostHelper.CreateValidationErrorDto(validationException);

            return(controller.BadRequest(error));
        }
 /// <summary>
 /// Returns a Bad request with data specific for this current system
 /// </summary>
 /// <param name="message">Message to send with the request</param>
 /// <returns></returns>
 public static IActionResult FixedBadRequest(this ControllerBase _base, string message = null)
 {
     return(_base.BadRequest(new HttpSingleResponse <object>
     {
         IsSuccess = false,
         Message = message
     }));
 }
Пример #23
0
        public static ActionResult <GenericApiResponse <object> > HandleBadRequest(this ControllerBase controller, string title, string error)
        {
            var response = new GenericApiResponse <object>();

            response.Error.title = title;
            response.Error.error = error;
            return(controller.BadRequest(response));
        }
        public static BadRequestObjectResult BadRequestResource(this ControllerBase controller, MediaType resource)
        {
            var result = controller.BadRequest(resource);

            result.ContentTypes.Add(resource.GetMediaType("restfulbank"));

            return(result);
        }
        internal static IActionResult ProcessRequest <TCommunicatorRequest>(
            [NotNull] this ControllerBase controllerBase,
            [CanBeNull] out TCommunicatorRequest request,
            out Guid apiKey) where TCommunicatorRequest : class, ICommunicatorRequest
        {
            if (controllerBase == null)
            {
                throw new ArgumentNullException(nameof(controllerBase));
            }

            Program.Logger.LogDebug("Processing request");

            request = null;
            apiKey  = Guid.Empty;

            if (!HeadersValid(controllerBase.Request.Headers))
            {
                return(controllerBase.BadRequest(
                           $"The request has invalid encoding (not {Encoding.UTF8.WebName}) or invalid content type " +
                           $"(not {MediaTypeNames.Application.Json})"));
            }

            Program.Logger.LogDebug("Headers are valid");

            if (!ParseBody(controllerBase, out request, out var actionResult))
            {
                return(actionResult);
            }

            Program.Logger.LogDebug("JSON is valid");

            var guidString   = request.ApiKey;
            var guidNullable = request.ApiKey.ToGuidOrNull();

            if (!guidNullable.HasValue)
            {
                return(controllerBase.BadRequest($"String {guidString} can't be parsed as GUID"));
            }

            Program.Logger.LogDebug("GUID is valid");
            apiKey = guidNullable.Value;
            Program.Logger.LogDebug($"Matching user by key. Inputted: {apiKey}. All users: ");
            Program.DataStorage.Users.ForEach(it => Program.Logger.LogDebug(it.ToString()));
            return(Program.HasUserWithApiKey(apiKey) ? null : controllerBase.StatusCode(403));
        }
Пример #26
0
        private IActionResult GenerateBadRequest(ServiceException e)
        {
            ErrorDto errorMessage = new ErrorDto()
            {
                ErrorMessage = e.Message
            };

            return(sender.BadRequest(errorMessage));
        }
Пример #27
0
        public static IActionResult GenerateResponse(this ControllerBase controllerBase, Response response)
        {
            if (response.Success)
            {
                return(controllerBase.Ok(response));
            }

            return(controllerBase.BadRequest(response));
        }
Пример #28
0
        private IActionResult GetCommandResponse <T>(T response, ControllerBase controller) where T : SimpleCommandResponseData
        {
            if (!response.IsValid)
            {
                return(controller.BadRequest(response));
            }

            return(controller.Ok(response));
        }
        private static ActionResult BadRequest(ControllerBase controller, IApiResponse response)
        {
            foreach (var error in response.ValidationErrors)
            {
                controller.ModelState.AddModelError(error.Identifier, error.ErrorMessage);
            }

            return(controller.BadRequest(controller.ModelState));
        }
Пример #30
0
        public static ActionResult Error(
            this ControllerBase controller,
            string error)
        {
            var dict = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            dict.AddModelError("error", error);
            return(controller.BadRequest(dict));
        }