public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddScoped <ITokenService, TokenService>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IBasketRepository, BasketRepository>(); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); return(services); }
private async Task HandleError(Func <Task> processRequest) { try { await processRequest(); } catch (ValidationApplicationException exception) { var response = new ValidationErrorResponse( exception.Message, exception.Failures); await Clients.Caller.SendAsync(_handleErrorName, response); } catch (ValidationDomainException exception) { var response = new ValidationErrorResponse( exception.Message, new Dictionary <string, string[]> { { exception.PropertyName, new[] { exception.Message } } }); await Clients.Caller.SendAsync(_handleErrorName, response); } catch (Exception exception) { await Clients.Caller.SendAsync(_handleErrorName, exception.ToString()); } }
private static void AddValidationErrors(ValidationErrorResponse validationErrorResponse, IList <ValidationFailure> failures) { validationErrorResponse.ValidationErrors.AddRange(failures.Select(e => new ValidationError { Name = e.PropertyName, Description = e.ErrorMessage })); }
public bool Accept(ValidationErrorResponse validationError) { Accept(validationError as ResponseModel); foreach (var error in validationError.ValidationErrors) { _modelState.AddModelError(error.Key, error.Value); } return(false); }
private async Task HandleExceptionAsync(HttpContext context, ValidationApplicationException exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.Body.FlushAsync(); var response = new ValidationErrorResponse(exception.Message, exception.Failures); var result = JsonConvert.SerializeObject(response); await context.Response.WriteAsync(result); }
private async Task <ValidationErrorResponse> ValidateCreateNote(CreateNoteDto note) { ValidationErrorResponse validationErrorResponse = new ValidationErrorResponse(null, null, new List <ValidationError>()); var validation = _createNoteValidator.Validate(note); if (validation?.IsValid == false) { AddValidationErrors(validationErrorResponse, validation.Errors); } return(validationErrorResponse); }
private async Task <ValidationErrorResponse> ValidateUpdateUser(UpdateUserDto user) { ValidationErrorResponse validationErrorResponse = new ValidationErrorResponse(null, null, new List <ValidationError>()); var validation = _updateUserValidator.Validate(user); if (validation?.IsValid == false) { AddValidationErrors(validationErrorResponse, validation.Errors); } return(validationErrorResponse); }
private async Task HandleExceptionAsync(HttpContext context, AuthenticationApplicationException exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.Body.FlushAsync(); var response = new ValidationErrorResponse( exception.Message, new Dictionary <string, string[]>()); var result = JsonConvert.SerializeObject(response); await context.Response.WriteAsync(result); }
private static bool HandleDataConstraintException(ApiController ctrl, Exception error, TaskCompletionSource <IHttpActionResult> tcs) { var sqlViolationError = error as UniqueKeyViolationException; if (null != sqlViolationError) { var response = new ValidationErrorResponse { Message = "Unique constraint violation", Details = new[] { sqlViolationError.Message } }; tcs.TrySetResult(new NegotiatedContentResult <ValidationErrorResponse>((HttpStatusCode)422, response, ctrl)); return(true); } return(false); }
private static bool HandleValidationException(ApiController ctrl, Exception error, TaskCompletionSource <IHttpActionResult> tcs) { var validationError = error as ValidationException; if (null != validationError) { var response = new ValidationErrorResponse { Message = error.Message, Details = validationError.Errors.Select(p => p.ErrorMessage).ToArray() }; tcs.TrySetResult(new NegotiatedContentResult <ValidationErrorResponse>((HttpStatusCode)422, response, ctrl)); return(true); } return(false); }
private async Task HandleExceptionAsync(HttpContext context, ApplicationException exception) { context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status400BadRequest; await context.Response.Body.FlushAsync(); var response = new ValidationErrorResponse( exception.Message, new Dictionary <string, string[]> { { exception.PropertyName, new[] { exception.Message } } }); var result = JsonConvert.SerializeObject(response); await context.Response.WriteAsync(result); }
public static ValidationErrorResponse ToValidationErrorResponse(this ValidationException excetion) { var rsp = new ValidationErrorResponse { ErrorMessage = excetion.Message, Errors = excetion.Errors.Select(x => new ValidationErrorResponse.ValidationError { PropertyName = x.PropertyName, AttemptedValue = x.AttemptedValue, ErrorCode = x.ErrorCode, ErrorMessage = x.ErrorMessage, Severity = (ValidationErrorResponse.ErrorSeverity)(int) x.Severity }).ToArray() }; return(rsp); }
public void OnException(ExceptionContext context) { var exception = context.Exception; switch (exception) { case AdministrationDomainException domainException: { var validationError = new ValidationErrorResponse(domainException.ErrorCode, domainException.Message); context.Result = new BadRequestObjectResult(validationError); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; break; } case AdministrationApplicationNotFoundException notFoundException: { var validationError = new ValidationErrorResponse(notFoundException.ErrorCode, notFoundException.Message); context.Result = new NotFoundObjectResult(validationError); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound; break; } case AdministrationApplicationException applicationException: { var validationError = new ValidationErrorResponse(applicationException.ErrorCode, applicationException.Message); context.Result = new BadRequestObjectResult(validationError); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; break; } default: { var validationError = new ValidationErrorResponse(exception.Message); context.Result = new InternalServerErrorObjectResult(validationError); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; break; } } context.ExceptionHandled = true; }
protected virtual ObjectResult CreateValidationErrorsResponse(HttpRequest request, IReadOnlyCollection <string> errors, HttpStatusCode statusCode, string message, string code) #endif { Check.ArgumentIsNull(request, "request"); Check.ArgumentIsNull(errors, "errors"); Check.Argument(errors.Count > 0, "errors.Count > 0"); Check.ArgumentIsNullOrWhiteSpace(message, "message"); Check.ArgumentIsNullOrWhiteSpace(code, "code"); var response = new ValidationErrorResponse ( message: message, errors: errors.ToArray(), code: code ); return(CreateResponse(request, statusCode, response)); }
public async Task <IActionResult> ValidateAsync(CheckCashoutValidityModel model) { var cashoutModel = model != null ? new CashoutModel { AssetId = model.AssetId, DestinationAddress = model.DestinationAddress, Volume = model.Amount, ClientId = model.ClientId } : null; var validationErrors = await _validationService.ValidateAsync(cashoutModel); var response = new CashoutValidityResult { IsAllowed = (validationErrors?.Count ?? 0) == 0, ValidationErrors = validationErrors?.Select(x => ValidationErrorResponse.Create((ValidationErrorType)x.Type, x.Value)), }; return(Ok(response)); }
/// <summary> /// Checks whether or not cashout to the destination address is allowed /// </summary> /// <param name="validateCashoutModel"></param> /// <returns></returns> /// <exception cref="Exception">Is thrown on wrong usage of service.</exception> public async Task <(bool isAllowed, IEnumerable <ValidationErrorResponse>)> ValidateCashoutAsync(CheckCashoutValidityModel validateCashoutModel) { var isAllowed = false; IEnumerable <ValidationErrorResponse> validationErrors; try { var response = await _service.CashoutCheckAsync(validateCashoutModel); isAllowed = response.IsAllowed; validationErrors = response.ValidationErrors; } catch (ApiException e) { var error = GetErrorResponse(e); validationErrors = new[] { ValidationErrorResponse.Create(ValidationErrorType.None, error.Message), }; } return(isAllowed, validationErrors); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (CommandValidationException ex) { _logger.LogError(ex, "Command validation errors occured."); context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "application/json"; var response = new ValidationErrorResponse { Errors = ex.ValidationErrors }; await context.Response.WriteAsync(response.SerializeToJson(true)); } catch (DomainObjectNotFound ex) { _logger.LogError(ex, "Domain object not found exception."); context.Response.StatusCode = (int)HttpStatusCode.NotFound; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync(ex.Message); } catch (LibraryDomainException ex) { _logger.LogError(ex, "Library domain exception."); context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync(ex.Message); } catch (Exception ex) { _logger.LogError(ex, "Unhandled exception."); context.Response.StatusCode = (int) HttpStatusCode.InternalServerError; context.Response.ContentType = "text/plain; charset=utf-8"; await context.Response.WriteAsync(ex.Message); } }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!context.ModelState.IsValid) { var errorsInModelState = context.ModelState .Where(x => x.Value.Errors.Count > 0) .ToDictionary( kvp => kvp.Key, kvp => kvp.Value.Errors.Select(x => x.ErrorMessage).ToArray() ); var errorResponse = new ValidationErrorResponse(); foreach (var error in errorsInModelState) { foreach (var subError in error.Value) { if (errorResponse.Errors.Exists(x => x.FieldName == error.Key)) { errorResponse.Errors.Find(x => x.FieldName == error.Key).Errors.Add(subError); } else { var errorModel = new ValidationErrorModel { FieldName = error.Key, Errors = new List <string>(), }; errorModel.Errors.Add(subError); errorResponse.Errors.Add(errorModel); } } } context.Result = new UnprocessableEntityObjectResult(errorResponse); return; } await next(); }
public async Task InvokeAsync(HttpContext context) { try { // Call the next delegate/middleware in the pipeline await _next(context); } catch (FluentValidation.ValidationException ve) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.ContentType = "application/text"; var response = new ValidationErrorResponse(ve.Errors.Count(), ve.Errors.Select(x => new ValidationError(x.PropertyName, x.ErrorMessage, x.AttemptedValue))); var json = JsonSerializer.Serialize(response); _logger.LogInformation(json); await context.Response.WriteAsync(json); } catch (Exception ex) { _logger.LogError(ex, "An exception occured"); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "application/text"; await context.Response.WriteAsync($"Something went wrong!"); } }
/// <summary> /// Gets the repositories available from the source code host /// </summary> /// <param name='sourceHost'> /// The source host. Possible values include: 'github', 'bitbucket', 'vsts' /// </param> /// <param name='ownerName'> /// The name of the owner /// </param> /// <param name='appName'> /// The name of the application /// </param> /// <param name='vstsAccountName'> /// Filter repositories only for specified account and project, "vstsProjectId" /// is required /// </param> /// <param name='vstsProjectId'> /// Filter repositories only for specified account and project, /// "vstsAccountName" is required /// </param> /// <param name='form'> /// The selected form of the object. Possible values include: 'lite', 'full' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ValidationErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <SourceRepository> > > ListWithHttpMessagesAsync(string sourceHost, string ownerName, string appName, string vstsAccountName = default(string), string vstsProjectId = default(string), string form = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (sourceHost == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sourceHost"); } if (ownerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ownerName"); } if (appName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("sourceHost", sourceHost); tracingParameters.Add("vstsAccountName", vstsAccountName); tracingParameters.Add("vstsProjectId", vstsProjectId); tracingParameters.Add("form", form); tracingParameters.Add("ownerName", ownerName); tracingParameters.Add("appName", appName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/source_hosts/{source_host}/repositories").ToString(); _url = _url.Replace("{source_host}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(sourceHost, Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName)); _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName)); List <string> _queryParameters = new List <string>(); if (vstsAccountName != null) { _queryParameters.Add(string.Format("vstsAccountName={0}", System.Uri.EscapeDataString(vstsAccountName))); } if (vstsProjectId != null) { _queryParameters.Add(string.Format("vstsProjectId={0}", System.Uri.EscapeDataString(vstsProjectId))); } if (form != null) { _queryParameters.Add(string.Format("form={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(form, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ValidationErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ValidationErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ValidationErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <SourceRepository> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <IList <SourceRepository> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
protected BadRequestObjectResult HandleValidationException(ValidationException ex) { var response = new ValidationErrorResponse(ex.Errors.Select(e => new ValidationError(e.ErrorCode, e.PropertyName, e.ErrorMessage))); return(new BadRequestObjectResult(response)); }
/// <summary> /// Configures the repository for build /// </summary> /// <param name='repo'> /// The repository information /// </param> /// <param name='ownerName'> /// The name of the owner /// </param> /// <param name='appName'> /// The name of the application /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ValidationErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <SuccessResponse> > CreateOrUpdateWithHttpMessagesAsync(RepoInfo repo, string ownerName, string appName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (repo == null) { throw new ValidationException(ValidationRules.CannotBeNull, "repo"); } if (repo != null) { repo.Validate(); } if (ownerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ownerName"); } if (appName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("repo", repo); tracingParameters.Add("ownerName", ownerName); tracingParameters.Add("appName", appName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/repo_config").ToString(); _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName)); _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (repo != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(repo, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ValidationErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ValidationErrorResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ValidationErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <SuccessResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SuccessResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }