private static async Task <HttpResponseMessage> HandleChangeSetValidationException(
            HttpActionExecutedContext context,
            bool useVerboseErros,
            CancellationToken cancellationToken)
        {
            if (context.Exception is ChangeSetValidationException validationException)
            {
                var result = new
                {
                    error = new
                    {
                        code       = string.Empty,
                        innererror = new
                        {
                            message = validationException.Message,
                            type    = validationException.GetType().FullName
                        },
                        message           = "Validaion failed for one or more objects.",
                        validationentries = validationException.ValidationResults
                    },
                };

                var exceptionResult = new NegotiatedContentResult <object>(
                    (HttpStatusCode)422,
                    result,
                    context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    context.Request,
                    new MediaTypeFormatterCollection());

                return(await exceptionResult.ExecuteAsync(cancellationToken).ConfigureAwait(false));
            }

            return(null);
        }
        private static async Task <HttpResponseMessage> Handler400(
            HttpActionExecutedContext context,
            CancellationToken cancellationToken)
        {
            ValidationException validationException = context.Exception as ValidationException;

            if (validationException != null)
            {
                var exceptionResult = new NegotiatedContentResult <IEnumerable <ValidationResultDto> >(
                    HttpStatusCode.BadRequest,
                    validationException.ValidationResults.Select(r => new ValidationResultDto(r)),
                    context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    context.Request,
                    new MediaTypeFormatterCollection());
                return(await exceptionResult.ExecuteAsync(cancellationToken));
            }

            var odataException = context.Exception as ODataException;

            if (odataException != null)
            {
                return(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception));
            }

            return(null);
        }
        private static async Task <HttpResponseMessage> HandleChangeSetValidationException(
            HttpActionExecutedContext context,
            bool useVerboseErros,
            CancellationToken cancellationToken)
        {
            if (context.Exception is ChangeSetValidationException validationException)
            {
                var exceptionResult = new NegotiatedContentResult <IEnumerable <ValidationResultDto> >(
                    HttpStatusCode.BadRequest,
                    validationException.ValidationResults.Select(r => new ValidationResultDto(r)),
                    context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    context.Request,
                    new MediaTypeFormatterCollection());
                return(await exceptionResult.ExecuteAsync(cancellationToken).ConfigureAwait(false));
            }

            return(null);
        }
        private static async Task<HttpResponseMessage> HandleChangeSetValidationException(
           HttpActionExecutedContext context,
           bool useVerboseErros,
           CancellationToken cancellationToken)
        {
            ChangeSetValidationException validationException = context.Exception as ChangeSetValidationException;
            if (validationException != null)
            {
                var exceptionResult = new NegotiatedContentResult<IEnumerable<ValidationResultDto>>(
                    HttpStatusCode.BadRequest,
                    validationException.ValidationResults.Select(r => new ValidationResultDto(r)),
                    context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    context.Request,
                    new MediaTypeFormatterCollection());
                return await exceptionResult.ExecuteAsync(cancellationToken);
            }

            return null;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpError error = new HttpError(Exception, false);

            if (!Request.ShouldIncludeErrorDetail())
            {
                error.Add(HttpErrorKeys.MessageDetailKey, Exception.Message);
            }
            else
            {
                error.Add(HttpErrorKeys.ExceptionMessageKey, Exception.Message);
                error.Add(HttpErrorKeys.ExceptionTypeKey, Exception.GetType().FullName);
                error.Add(HttpErrorKeys.StackTraceKey, Exception.StackTrace);
                if (Exception.InnerException != null)
                {
                    error.Add(HttpErrorKeys.InnerExceptionKey, new HttpError(Exception.InnerException, true));
                }
            }
            var res = new NegotiatedContentResult <HttpError>(HttpStatusCode.InternalServerError, error, ContentNegotiator, Request, Formatters);

            return(res.ExecuteAsync(cancellationToken));
        }
        public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds()
        {
            // Arrange
            HttpStatusCode expectedStatusCode = CreateStatusCode();
            object expectedContent = CreateContent();
            ApiController controller = CreateController();
            MediaTypeFormatter expectedInputFormatter = CreateFormatter();
            MediaTypeFormatter expectedOutputFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter,
                expectedMediaType);

            Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) =>
                f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter ? true : false;

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter,
                    contentNegotiator))
                {
                    controller.Configuration = configuration;
                    controller.Request = expectedRequest;

                    IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent,
                        controller);

                    // Act
                    Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                    // Assert
                    Assert.NotNull(task);
                    task.WaitUntilCompleted();

                    using (HttpResponseMessage response = task.Result)
                    {
                        Assert.NotNull(response);
                        Assert.Equal(expectedStatusCode, response.StatusCode);
                        HttpContent content = response.Content;
                        Assert.IsType<ObjectContent<object>>(content);
                        ObjectContent<object> typedContent = (ObjectContent<object>)content;
                        Assert.Same(expectedContent, typedContent.Value);
                        Assert.Same(expectedOutputFormatter, typedContent.Formatter);
                        Assert.NotNull(typedContent.Headers);
                        Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                        Assert.Same(expectedRequest, response.RequestMessage);
                    }
                }
            }
        }
        public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails()
        {
            // Arrange
            HttpStatusCode statusCode = HttpStatusCode.Conflict;
            object content = CreateContent();
            ContentNegotiationResult negotiationResult = null;

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = new NegotiatedContentResult<object>(statusCode, content, contentNegotiator,
                    expectedRequest, expectedFormatters);

                // Act
                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }
        public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds()
        {
            // Arrange
            HttpStatusCode expectedStatusCode = CreateStatusCode();
            object expectedContent = CreateContent();
            MediaTypeFormatter expectedFormatter = CreateFormatter();
            MediaTypeHeaderValue expectedMediaType = CreateMediaType();
            ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType);

            using (HttpRequestMessage expectedRequest = CreateRequest())
            {
                IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters();

                Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>();
                spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns(
                    negotiationResult);
                IContentNegotiator contentNegotiator = spy.Object;

                IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent,
                    contentNegotiator, expectedRequest, expectedFormatters);

                // Act
                Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None);

                // Assert
                Assert.NotNull(task);
                task.WaitUntilCompleted();

                using (HttpResponseMessage response = task.Result)
                {
                    Assert.NotNull(response);
                    Assert.Equal(expectedStatusCode, response.StatusCode);
                    HttpContent content = response.Content;
                    Assert.IsType<ObjectContent<object>>(content);
                    ObjectContent<object> typedContent = (ObjectContent<object>)content;
                    Assert.Same(expectedContent, typedContent.Value);
                    Assert.Same(expectedFormatter, typedContent.Formatter);
                    Assert.NotNull(typedContent.Headers);
                    Assert.Equal(expectedMediaType, typedContent.Headers.ContentType);
                    Assert.Same(expectedRequest, response.RequestMessage);
                }
            }
        }