protected virtual IHttpActionResult GetErrorResult(IdentityResult result, ErrorCode errorCode) { if (result == null) { return(InternalServerError()); } if (!result.Succeeded) { var httpError = new HttpError(); if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return(BadRequest()); } httpError.Add("CustomErrorCode", (int)errorCode); httpError.Add("ModelState", ModelState.Values.Select(x => x.Errors.Select(e => e.ErrorMessage))); var response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); return(ResponseMessage(response)); } return(null); }
public override void OnException(HttpActionExecutedContext context) { if (context.Exception is ModelException) { ModelException exception = (ModelException)context.Exception; HttpError error = new HttpError(); error.Add("Message", "An error has occurred."); error.Add("ExceptionMessage", exception.Message); error.Add("ExceptionCode", exception.ExceptionCode); error.Add("ExceptionType", exception.Source); error.Add("StackTrace", exception.StackTrace); context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Exception is AnecdoteException) { AnecdoteException exception = ((AnecdoteException)actionExecutedContext.Exception); HttpError error = new HttpError(); error.Add("ExceptionMessage", exception.Message); error.Add("ExceptionType", exception.Source); //error.Add("StackTrace", exception.StackTrace); actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(exception.StatusCode, error); } }
protected HttpResponseMessage ProcessResultResponse(HandlerResult result) { var response = new HttpResponseMessage(result.StatusCode); if (!String.IsNullOrWhiteSpace(result.ReasonPhrase)) { response.ReasonPhrase = result.ReasonPhrase; } if (result.Headers != null) { foreach (var header in result.Headers) { response.Headers.TryAddWithoutValidation(header.Key, header); } } if (result.ErrorInformation != null && !String.IsNullOrWhiteSpace(result.ErrorInformation.ErrorCode)) { var error = new HttpError { { "Code", result.ErrorInformation.ErrorCode }, { "Message", result.ErrorInformation.ErrorMessage }, }; foreach (var msg in result.ErrorInformation.AdditionalDetails) { error.Add(msg.Key, msg.Value); } response.Content = new ObjectContent <HttpError>(error, GlobalConfiguration.Configuration.Formatters.XmlFormatter, "application/xml"); } return(response); }
private HttpResponseMessage Execute() { var httpResponseMessage = new HttpResponseMessage(); try { var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters); if (negotiationResult == null) { httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable; } else { var error = new HttpError("Internal Server Error"); foreach (var property in Exception.GetCustomProperties()) { error.Add(property.Key, property.Value); } httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError; httpResponseMessage.Content = new ObjectContent <HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType); } httpResponseMessage.RequestMessage = Request; } catch { httpResponseMessage.Dispose(); throw; } return(httpResponseMessage); }
/// <summary> /// An exception /// </summary> /// <param name="actionExecutedContext"></param> public override void OnException(HttpActionExecutedContext actionExecutedContext) { HttpStatusCode code; HttpError error = new HttpError(); // Various exception cases if (actionExecutedContext.Exception is ArgumentException) { var ex = actionExecutedContext.Exception as ArgumentException; code = HttpStatusCode.BadRequest; } else if (actionExecutedContext.Exception is SqlException) { var ex = actionExecutedContext.Exception as SqlException; code = HttpStatusCode.BadRequest; } else { var ex = actionExecutedContext.Exception as Exception; code = HttpStatusCode.InternalServerError; } // Setting the error response error.Add("Error", actionExecutedContext.Exception.Message); actionExecutedContext.Response = actionExecutedContext.ActionContext.Request.CreateErrorResponse(code, error); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting(HttpActionContext actionContext) { ModelStateDictionary modelState = actionContext.ModelState; IEntity valueArg = null; if (actionContext.ActionArguments.ContainsKey("value")) { valueArg = actionContext.ActionArguments["value"] as IEntity; } if (valueArg != null) { Type entityType = actionContext.ActionArguments["value"].GetType(); IgnoreModelErrorsAttribute ignoreModelErrorsAttribute = entityType.GetCustomAttributes(typeof(IgnoreModelErrorsAttribute), true).FirstOrDefault() as IgnoreModelErrorsAttribute; if (ignoreModelErrorsAttribute != null) { foreach (string key in ignoreModelErrorsAttribute.Keys) { IEnumerable <string> matchingKeys = modelState.Keys.Where(x => Regex.IsMatch(x, key)); foreach (string matchingKey in matchingKeys) { modelState[matchingKey].Errors.Clear(); } } } } if (!actionContext.ModelState.IsValid) { HttpError httpError = new HttpError(); foreach (var item in actionContext.ModelState) { var msg = new System.Text.StringBuilder(); foreach (ModelError error in item.Value.Errors) { if (!string.IsNullOrWhiteSpace(error.ErrorMessage)) { msg.Append(msg.Length > 0 ? "; " : ""); msg.Append(error.ErrorMessage); } if (error.Exception != null && !string.IsNullOrWhiteSpace(error.Exception.Message)) { msg.Append(msg.Length > 0 ? "; " : ""); msg.Append(error.Exception.Message); } } httpError.Add(item.Key, msg.ToString()); } actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } }
internal static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail) { HttpError error = new HttpError(message); if (request.ShouldIncludeErrorDetail()) { error.Add(MessageDetailKey, messageDetail); } return request.CreateErrorResponse(statusCode, error); }
internal async Task <HttpResponseMessage> SendFluentApiAsync(HttpRequestMessage request, CancellationToken cancellationToken, HttpControllerDescriptor controllerDescriptor) { ExceptionDispatchInfo exceptionInfo; HttpControllerContext controllerContext = null; try { IHttpController controller = controllerDescriptor.CreateController(request); if (controller == null) { var httpError = new HttpError(string.Format(CultureInfo.CurrentCulture, "No HTTP resource was found that matches the request URI '{0}'.", request.RequestUri)); if (request.ShouldIncludeErrorDetail()) { httpError.Add(HttpErrorKeys.MessageDetailKey, "No controller was created to handle this request."); } return(request.CreateErrorResponse(HttpStatusCode.NotFound, httpError)); } controllerContext = CreateControllerContext(request, controllerDescriptor, controller); return(await controller.ExecuteAsync(controllerContext, cancellationToken)); } catch (OperationCanceledException) { // Propogate the canceled task without calling exception loggers or handlers. throw; } catch (HttpResponseException httpResponseException) { return(httpResponseException.Response); } catch (Exception exception) { exceptionInfo = ExceptionDispatchInfo.Capture(exception); } Debug.Assert(exceptionInfo.SourceException != null); ExceptionContext exceptionContext = new ExceptionContext( exceptionInfo.SourceException, ExceptionCatchBlocks.HttpControllerDispatcher, request) { ControllerContext = controllerContext, }; await ExceptionLogger.LogAsync(exceptionContext, cancellationToken); HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext, cancellationToken); if (response == null) { exceptionInfo.Throw(); } return(response); }
internal static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail) { HttpError error = new HttpError(message); HttpConfiguration config = request.GetConfiguration(); if (config != null && ShouldIncludeErrorDetail(config, request)) { error.Add(MessageDetailKey, messageDetail); } return request.CreateErrorResponse(statusCode, error); }
internal static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail) { HttpError error = new HttpError(message); HttpConfiguration config = request.GetConfiguration(); if (config != null && ShouldIncludeErrorDetail(config, request)) { error.Add(MessageDetailKey, messageDetail); } return(request.CreateErrorResponse(statusCode, error)); }
public static HttpResponseMessage ConverToHttpResponse(HttpActionExecutedContext context) { var exception = context.Exception; var error = new HttpError(); var dic = ExceptionConvertorService.Convert(exception); foreach (var item in dic) { error.Add(item.Key, item.Value); } return(context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error)); }
public static HttpResponseMessage ConverToHttpResponse(HttpActionExecutedContext context) { var exception = context.Exception; var error = new HttpError(); var dic = ExceptionConverterService.Convert(exception); foreach (var item in dic) { error.Add(item.Key, item.Value); } return context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting(HttpActionContext actionContext) { ModelStateDictionary modelState = actionContext.ModelState; IEntity valueArg = null; if (actionContext.ActionArguments.ContainsKey("value")) { valueArg = actionContext.ActionArguments["value"] as IEntity; } if (valueArg != null) { Type entityType = actionContext.ActionArguments["value"].GetType(); IgnoreModelErrorsAttribute ignoreModelErrorsAttribute = entityType.GetCustomAttributes(typeof(IgnoreModelErrorsAttribute), true).FirstOrDefault() as IgnoreModelErrorsAttribute; if (ignoreModelErrorsAttribute != null) { foreach (string key in ignoreModelErrorsAttribute.Keys) { IEnumerable <string> matchingKeys = modelState.Keys.Where(x => Regex.IsMatch(x, key)); foreach (string matchingKey in matchingKeys) { modelState[matchingKey].Errors.Clear(); } } } } if (!actionContext.ModelState.IsValid) { HttpError httpError = new HttpError(); foreach (var item in actionContext.ModelState) { foreach (ModelError error in item.Value.Errors) { if (!httpError.ContainsKey(item.Key)) { httpError.Add(item.Key, string.Empty); httpError[item.Key] += error.ErrorMessage; } else { httpError[item.Key] += Environment.NewLine + error.ErrorMessage; } } } actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, httpError); } }
public static HttpResponseMessage CreateErrorCodeResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, JObject additionalInfo = null) { var error = new HttpError(message) { { "Code", statusCode } }; if (additionalInfo != null) { error.Add("AdditionalInfo", additionalInfo); } return(request.CreateErrorResponse(statusCode, error)); }
/// <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 HttpResponseMessage Post(Product product) { if (!ModelState.IsValid) { HttpError error = new HttpError(ModelState, false); error.Message = "Cannot Add Product"; error.Add("AvailbleIDs", products.Select(x => x.ProductID)); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error)); } product.ProductID = products.Count + 1; products.Add(product); return(Request.CreateResponse(product)); }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="HttpResponseMessage" /> representing an error /// with an instance of <see cref="ObjectContent{T}" /> wrapping an <see cref="HttpError" /> with message <paramref name="message" /> /// and error code <paramref name="errorCode" /> if provided. /// If no formatter is found, this method returns a response with status 406 NotAcceptable. /// </summary> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="errorCode">The error code</param> /// <param name="message">The error message.</param> /// <returns> /// An error response with error message <paramref name="message" />, error code <paramref name="errorCode" /> (if provided) /// and status code <paramref name="statusCode" />. /// </returns> /// <remarks> /// This method requires that <paramref name="request" /> has been associated with an instance of /// <see cref="HttpConfiguration" />. /// </remarks> public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string errorCode, string message) { var err = new HttpError { { "errorMessage", message } }; if (!string.IsNullOrWhiteSpace(errorCode)) { err.Add("errorID", errorCode); } return(request.CreateErrorResponse(statusCode, err)); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting( HttpActionContext actionContext ) { ModelStateDictionary modelState = actionContext.ModelState; IEntity valueArg = null; if ( actionContext.ActionArguments.ContainsKey( "value" ) ) { valueArg = actionContext.ActionArguments["value"] as IEntity; } if ( valueArg != null ) { Type entityType = actionContext.ActionArguments["value"].GetType(); IgnoreModelErrorsAttribute ignoreModelErrorsAttribute = entityType.GetCustomAttributes( typeof( IgnoreModelErrorsAttribute ), true ).FirstOrDefault() as IgnoreModelErrorsAttribute; if ( ignoreModelErrorsAttribute != null ) { foreach ( string key in ignoreModelErrorsAttribute.Keys ) { IEnumerable<string> matchingKeys = modelState.Keys.Where( x => Regex.IsMatch( x, key ) ); foreach ( string matchingKey in matchingKeys ) { modelState[matchingKey].Errors.Clear(); } } } } if ( !actionContext.ModelState.IsValid ) { HttpError httpError = new HttpError(); foreach ( var item in actionContext.ModelState ) { foreach ( ModelError error in item.Value.Errors ) { if ( !httpError.ContainsKey( item.Key ) ) { httpError.Add( item.Key, string.Empty ); httpError[item.Key] += error.ErrorMessage; } else { httpError[item.Key] += Environment.NewLine + error.ErrorMessage; } } } actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, httpError ); } }
public override void Handle(ExceptionHandlerContext context) { const string Message = "Your input conflicted with the current state of the system."; if (context.Exception is DivideByZeroException) { context.Result = new ResponseMessageResult(context.Request.CreateErrorResponse(HttpStatusCode.Conflict, Message)); } else { HttpError error = new HttpError("An interval server error occured."); error.Add("CorrelationId", context.Request.GetCorrelationId().ToString()); var response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); context.Result = new ResponseMessageResult(response); } }
//public void Delete(int id) public HttpResponseMessage Delete(int id) { /*var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) * { * Content = new StringContent(Resources.Resources.IdDoesNotExistException + " Id: " + id), * };*/ var modelStateError = new HttpError(); modelStateError.Add("IdDoesNotExistException", Resources.Resources.IdDoesNotExistException + " Id: " + id); //return Request.CreateResponse(HttpStatusCode.BadRequest, modelStateError); throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, modelStateError)); }
public static HttpError CreateHttpError <T>(this T exception) where T : Exception { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly; var properties = exception.GetType().GetProperties(bindingFlags); var httpError = new HttpError(); foreach (var propertyInfo in properties) { httpError.Add(propertyInfo.Name, propertyInfo.GetValue(exception, null)); } return(httpError); }
/// Creates an HttpResponseMessage instance asynchronously. This method determines how a HttpResponseMessage content will look like. public override Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var result = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters); var message = new HttpResponseMessage { RequestMessage = Request, StatusCode = result != null ? HttpStatusCode.InternalServerError : HttpStatusCode.NotAcceptable, }; if (result != null) { string alert = null; if (Exception is SqlException) { // Strip the beginning of the exception message which contains the name of the stored procedure and the argument values. We do not disclose the values to the client. var index = Exception.Message.IndexOf("::"); // The magic separator used within our stored procedures. if (index >= 0) { alert = Exception.Message.Substring(index + 2).Trim(); } } else if (Exception is UserAlertException) { alert = Exception.Message; } // Until we have converted all the exceptions thrown by our code to UserAlertException else { alert = Exception.Message; } var content = new HttpError(Exception, IncludeErrorDetail); if (!String.IsNullOrEmpty(alert)) { // Define an additional content field. content.Add("Alert", alert); } // serializes the HttpError instance either to JSON or to XML depend on requested by the client MIME type. message.Content = new ObjectContent <HttpError>(content, result.Formatter, result.MediaType); } return(Task.FromResult(message)); }
public HttpResponseMessage GetCar(int id) { if ((id % 2) != 0) { var httpError = new HttpError(); httpError.Add("id", "Only \"even numbers\" are accepted as id."); return(Request.CreateErrorResponse( HttpStatusCode.InternalServerError, httpError)); } return(Request.CreateResponse( HttpStatusCode.OK, string.Format("Car {0}", id))); }
private static HttpResponseException CreateException(HttpStatusCode status, string message, string parameter = null, HttpRequestMessage requestMessage = null) { var httpError = new HttpError(message); if (!string.IsNullOrEmpty(parameter)) { httpError.Add("Parameter", parameter); } var msg = new HttpResponseMessage(status) { Content = new ObjectContent <HttpError>(httpError, GlobalConfiguration.Configuration.Formatters.JsonFormatter), RequestMessage = requestMessage }; return(new HttpResponseException(msg)); }
private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, Exception ex, HttpStatusCode statusCode) { HttpConfiguration configuration = request.GetConfiguration(); HttpError error = new HttpError(ex, request.ShouldIncludeErrorDetail()); string lastId = _coreLastReferenceIdManager.GetLastReferenceId(); if (!String.IsNullOrEmpty(lastId)) error.Add("Reference", lastId); // CreateErrorResponse should never fail, even if there is no configuration associated with the request // In that case, use the default HttpConfiguration to con-neg the response media type if (configuration == null) { using (HttpConfiguration defaultConfig = new HttpConfiguration()) { return request.CreateResponse(statusCode, error, defaultConfig); } } return request.CreateResponse(statusCode, error, configuration); }
private HttpResponseMessage Execute() { var httpResponseMessage = new HttpResponseMessage(); try { var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters); if (negotiationResult == null) { httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable; } else { var error = new HttpError("Validation Failed"); foreach (var err in _exception.ValidationErrors) { if (!error.ContainsKey(err.ItemName)) { error.Add(err.ItemName, new Collection <ApiError>()); } ((ICollection <ApiError>)error[err.ItemName]).Add(new ApiError { ErrorCode = err.ErrorCode, Message = err.ErrorMessage }); } httpResponseMessage.StatusCode = HttpStatusCode.BadRequest; httpResponseMessage.Content = new ObjectContent <HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType); } httpResponseMessage.RequestMessage = Request; } catch { httpResponseMessage.Dispose(); throw; } return(httpResponseMessage); }
private HttpResponseMessage CreateErrorResponse(HttpRequestMessage request, Exception ex, HttpStatusCode statusCode) { HttpConfiguration configuration = request.GetConfiguration(); HttpError error = new HttpError(ex, request.ShouldIncludeErrorDetail()); string lastId = _coreLastReferenceIdManager.GetLastReferenceId(); if (!String.IsNullOrEmpty(lastId)) { error.Add("Reference", lastId); } // CreateErrorResponse should never fail, even if there is no configuration associated with the request // In that case, use the default HttpConfiguration to con-neg the response media type if (configuration == null) { using (HttpConfiguration defaultConfig = new HttpConfiguration()) { return(request.CreateResponse(statusCode, error, defaultConfig)); } } return(request.CreateResponse(statusCode, error, configuration)); }
/// <summary> /// Helper method that performs content negotiation and creates a <see cref="T:System.Net.Http.HttpResponseMessage"/> /// representing an error with an instance of <see cref="T:System.Net.Http.ObjectContent`1"/> wrapping an /// <see cref="T:System.Web.Http.HttpError"/> with message <paramref name="message"/> and message detail /// <paramref name="messageDetail"/>. If no formatter is found, this method returns a response with /// status 406 NotAcceptable. /// </summary> /// <remarks> /// This method requires that <paramref name="request"/> has been associated with an instance of /// <see cref="T:System.Web.Http.HttpConfiguration"/>. /// </remarks> /// <param name="request">The request.</param> /// <param name="statusCode">The status code of the created response.</param> /// <param name="message">The error message. This message will always be seen by clients.</param> /// <param name="messageDetail">The error message detail. This message will only be seen by clients if we should include error detail.</param> /// <returns>An error response with error message <paramref name="message"/> and message detail <paramref name="messageDetail"/> /// and status code <paramref name="statusCode"/>.</returns> /// <exception cref="T:System.ArgumentNullException">request /// or /// message</exception> public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request, HttpStatusCode statusCode, string message, string messageDetail) { Throw.IfArgumentNull(request, "request"); Throw.IfArgumentNullOrEmpty(message, "message"); HttpConfiguration configuration = request.GetConfiguration(); // CreateErrorResponse should never fail, even if there is no configuration associated with the request // In that case, use the default HttpConfiguration to con-neg the response media type if (configuration == null) { configuration = new HttpConfiguration(); } bool includeDetail = configuration != null?configuration.ShouldIncludeErrorDetail(request) : new HttpConfiguration().ShouldIncludeErrorDetail(request); HttpError error = new HttpError(message); if (includeDetail) { error.Add("MessageDetail", messageDetail); } return(request.CreateResponse <HttpError>(statusCode, error, configuration)); }
public static HttpResponseMessage CreateErrorResponse(this HttpActionContext context, HttpStatusCode statusCode, string errorCode, string message) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Request != null) { return(context.Request.CreateErrorResponse(statusCode, errorCode, message)); } var err = new HttpError { { "errorMessage", message } }; if (!string.IsNullOrWhiteSpace(errorCode)) { err.Add("errorID", errorCode); } return(ReturnResponseMessageWithContent(statusCode, err)); }
public async Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { var ex = actionExecutedContext.Exception as ApiException; if (ex == null) { return; } //var errorModel = new ErrorModel {Message = ex.Message, Data = ex.ErrorData}; var errorModel = new HttpError(ex.Message) { { "ErrorCode", ex.ErrorCode } }; if (ex.ErrorData != null) { errorModel.Add("ErrorData", ex.ErrorData); } var response = actionExecutedContext.Request.CreateErrorResponse(ex.StatusCode, errorModel); actionExecutedContext.Response = response; //actionExecutedContext.Exception = null; }
/// <summary> /// Fetches a HttpError from a model state /// </summary> /// <param name="modelState"></param> /// <param name="includeErrorDetail"></param> /// <returns></returns> private HttpError GetErrors(ModelStateDictionary modelState, bool includeErrorDetail) { var modelStateError = new HttpError(); foreach (KeyValuePair <string, ModelState> keyModelStatePair in modelState) { string key = keyModelStatePair.Key; ModelErrorCollection errors = keyModelStatePair.Value.Errors; if (errors != null && errors.Count > 0) { IEnumerable <string> errorMessages = errors.Select(error => { if (includeErrorDetail && error.Exception != null) { return(error.Exception.Message); } return(String.IsNullOrEmpty(error.ErrorMessage) ? "ErrorOccurred" : error.ErrorMessage); }).ToArray(); modelStateError.Add(key, errorMessages); } } return(modelStateError); }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting( HttpActionContext actionContext ) { ModelStateDictionary modelState = actionContext.ModelState; //// Remove any model errors that should be ignored based on IgnoreModelErrorsAttribute // determine the entity parameter so we can clear the model errors on the ignored properties IEntity valueArg = null; if ( actionContext.ActionArguments.Count > 0 ) { // look a parameter with the name 'value', if not found, get the first parameter that is an IEntity if ( actionContext.ActionArguments.ContainsKey( "value" ) ) { valueArg = actionContext.ActionArguments["value"] as IEntity; } else { valueArg = actionContext.ActionArguments.Select( a => a.Value ).Where( a => a is IEntity ).FirstOrDefault() as IEntity; } } // if we found the entityParam, clear the model errors on ignored properties if ( valueArg != null ) { Type entityType = valueArg.GetType(); IgnoreModelErrorsAttribute ignoreModelErrorsAttribute = entityType.GetCustomAttributes( typeof( IgnoreModelErrorsAttribute ), true ).FirstOrDefault() as IgnoreModelErrorsAttribute; if ( ignoreModelErrorsAttribute != null ) { foreach ( string key in ignoreModelErrorsAttribute.Keys ) { IEnumerable<string> matchingKeys = modelState.Keys.Where( x => Regex.IsMatch( x, key ) ); foreach ( string matchingKey in matchingKeys ) { modelState[matchingKey].Errors.Clear(); } } } } // now that the IgnoreModelErrorsAttribute properties have been cleared, deal with the remaining model state validations if ( !actionContext.ModelState.IsValid ) { HttpError httpError = new HttpError(); foreach ( var item in actionContext.ModelState ) { var msg = new System.Text.StringBuilder(); foreach ( ModelError error in item.Value.Errors ) { if ( !string.IsNullOrWhiteSpace( error.ErrorMessage ) ) { msg.Append( msg.Length > 0 ? "; " : "" ); msg.Append( error.ErrorMessage ); } if ( error.Exception != null && !string.IsNullOrWhiteSpace( error.Exception.Message ) ) { msg.Append( msg.Length > 0 ? "; " : "" ); msg.Append( error.Exception.Message ); } } httpError.Add( item.Key, msg.ToString() ); } actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, httpError ); } }
private HttpResponseMessage Execute() { var httpResponseMessage = new HttpResponseMessage(); try { var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters); if (negotiationResult == null) { httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable; } else { var error = new HttpError("Validation Failed"); foreach (var err in _exception.ValidationErrors) { if (!error.ContainsKey(err.ItemName)) { error.Add(err.ItemName, new Collection<ApiError>()); } ((ICollection<ApiError>)error[err.ItemName]).Add(new ApiError { ErrorCode = err.ErrorCode, Message = err.ErrorMessage }); } httpResponseMessage.StatusCode = HttpStatusCode.BadRequest; httpResponseMessage.Content = new ObjectContent<HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType); } httpResponseMessage.RequestMessage = Request; } catch { httpResponseMessage.Dispose(); throw; } return httpResponseMessage; }
/// <summary> /// Occurs before the action method is invoked. /// </summary> /// <param name="actionContext">The action context.</param> public override void OnActionExecuting( HttpActionContext actionContext ) { ModelStateDictionary modelState = actionContext.ModelState; IEntity valueArg = null; if ( actionContext.ActionArguments.ContainsKey( "value" ) ) { valueArg = actionContext.ActionArguments["value"] as IEntity; } if ( valueArg != null ) { Type entityType = actionContext.ActionArguments["value"].GetType(); IgnoreModelErrorsAttribute ignoreModelErrorsAttribute = entityType.GetCustomAttributes( typeof( IgnoreModelErrorsAttribute ), true ).FirstOrDefault() as IgnoreModelErrorsAttribute; if ( ignoreModelErrorsAttribute != null ) { foreach ( string key in ignoreModelErrorsAttribute.Keys ) { IEnumerable<string> matchingKeys = modelState.Keys.Where( x => Regex.IsMatch( x, key ) ); foreach ( string matchingKey in matchingKeys ) { modelState[matchingKey].Errors.Clear(); } } } } if ( !actionContext.ModelState.IsValid ) { HttpError httpError = new HttpError(); foreach ( var item in actionContext.ModelState ) { var msg = new System.Text.StringBuilder(); foreach ( ModelError error in item.Value.Errors ) { if ( !string.IsNullOrWhiteSpace( error.ErrorMessage ) ) { msg.Append( msg.Length > 0 ? "; " : "" ); msg.Append( error.ErrorMessage ); } if ( error.Exception != null && !string.IsNullOrWhiteSpace( error.Exception.Message ) ) { msg.Append( msg.Length > 0 ? "; " : "" ); msg.Append( error.Exception.Message ); } } httpError.Add( item.Key, msg.ToString() ); } actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, httpError ); } }
private HttpResponseMessage Execute() { var httpResponseMessage = new HttpResponseMessage(); try { var negotiationResult = ContentNegotiator.Negotiate(typeof(HttpError), Request, Formatters); if (negotiationResult == null) { httpResponseMessage.StatusCode = HttpStatusCode.NotAcceptable; } else { var error = new HttpError("Internal Server Error"); foreach (var property in Exception.GetCustomProperties()) { error.Add(property.Key, property.Value); } httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError; httpResponseMessage.Content = new ObjectContent<HttpError>(error, negotiationResult.Formatter, negotiationResult.MediaType); } httpResponseMessage.RequestMessage = Request; } catch { httpResponseMessage.Dispose(); throw; } return httpResponseMessage; }
public HttpResponseMessage GetBalance(string version, string appId, string customerId, string AccountNumber) { DataSet ds = new DataSet(); getBalanceRequest.version = version; getBalanceRequest.appID = appId; getBalanceRequest.customerID = customerId; getBalanceRequest.AccountNumber = AccountNumber; try { // DataSet ds = new DataSet(); string URL = "Balance/GetBalance&version?" + version + "&customerId?" + customerId + "&AccountNumber?" + AccountNumber + ""; ds = c.getInserlogrequest(URL); getBalanceResponse = APIBanking.DomesticRemittanceClient.getBalance(env, getBalanceRequest); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(getBalanceResponse.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, getBalanceResponse); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes.ToString()); // c.writelog(e.Message, "FaultException", DateTime.Now, "", ""); return(this.Request.CreateResponse(HttpStatusCode.OK, getBalanceResponse)); } catch (MessageSecurityException e) { Fault fault = new Fault(new APIBanking.Fault(e)); HttpError myCustomError = new HttpError(fault.Message); c.writelog(e.Message, "MessageSecurityException", DateTime.Now, "", ""); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError)); } catch (TimeoutException ex) { HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", 500); myCustomError.Add("Errormsg", ex.Message); myCustomError.Add("Ihno", AccountNumber); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); //c.InsertResponse("500", ex.Message, requestReferenceNo, ""); c.writelog(ex.Message, "TimeoutException", DateTime.Now, "", ""); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError)); } catch (FaultException ex) { String faultCode = ex.Code.SubCode.Name; String FaultReason = ex.Message; message = faultCode + " - " + FaultReason; HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", faultCode); myCustomError.Add("Errormsg", FaultReason); myCustomError.Add("Ihno", AccountNumber); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); //c.InsertResponse(faultCode, FaultReason, requestReferenceNo, ""); c.writelog(ex.Message, "FaultException", DateTime.Now, "", ""); return(Request.CreateResponse(HttpStatusCode.ExpectationFailed, myCustomError)); } catch (CommunicationException ex) { HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", 500); myCustomError.Add("Errormsg", ex.Message); myCustomError.Add("Ihno", AccountNumber); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); c.writelog(ex.Message, "CommunicationException", DateTime.Now, "", ""); //c.InsertResponse("500", ex.Message, requestReferenceNo, ""); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError)); } catch (Exception ex) { HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", 500); myCustomError.Add("Errormsg", "InternerlServer Error"); myCustomError.Add("Ihno", AccountNumber); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); //c.InsertResponse("500", ex.Message, requestReferenceNo, ""); c.writelog(ex.Message, "Exception", DateTime.Now, "", ""); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError)); } //return getBalanceResponse; }
public HttpResponseMessage TransferBal(string beneficiaryAccountNo, string beneficiaryIFSC, string beneficiaryMMID, string beneficiaryMobileNo, string Name, string address1, string emailID, string mobileNo, string uniqueRequestNo, string appID, string customerID, string debitAccountNo, float transferAmount) { DataSet ds = new DataSet(); string URL = "Transfer/TransferBal&beneficiaryAccountNo?" + beneficiaryAccountNo + "&beneficiaryIFSC?" + beneficiaryIFSC + "&beneficiaryMMID?" + beneficiaryMMID + "&beneficiaryMobileNo?" + beneficiaryMobileNo + "&Name?" + Name + "&address1?" + address1 + "&emailID?" + emailID + "&mobileNo?" + mobileNo + "&uniqueRequestNo?" + uniqueRequestNo + "&appID?" + appID + "&customerID?" + customerID + "&debitAccountNo?" + debitAccountNo + "&transferAmount?" + transferAmount + ""; ds = c.getInserlogrequest(URL); APIBanking.Environment env = new APIBanking.Environments.YBL.UAT("2449810", "Yesbank1", "7a7a26d8-1679-436b-854a-a2b5682bbf11", "nP8oE0tO5wR5kI1qD3aA6aR6wD6hR7hB8oP6qW5vU0hN0wE4sD", null); // APIBanking.Environment env = new APIBanking.Environments.YBL.UAT(ConfigurationManager.AppSettings["customerId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString(), ConfigurationManager.AppSettings["clientId"].ToString(), ConfigurationManager.AppSettings["clientSecret"].ToString(), ConfigurationManager.AppSettings["CertificatePath"].ToString(), "123"); com.transfer gTransfer = new transfer(); com.transferRequest gTransferRequest = new transferRequest(); com.transferResponse gTransferResponse = new transferResponse(); beneficiaryDetailType b = new beneficiaryDetailType(); b.beneficiaryAccountNo = beneficiaryAccountNo; b.beneficiaryIFSC = beneficiaryIFSC; b.beneficiaryMMID = beneficiaryMMID; b.beneficiaryMobileNo = beneficiaryMobileNo; beneficiaryType bt = new beneficiaryType(); nameType nm = new nameType(); nm.Item = Name; AddressType ad = new AddressType(); ad.address1 = address1; //ad.address2 = ""; // ad.address3 = ""; // ad.city = ""; ad.country = "IN"; //ad.postalCode = ""; contactType ct = new contactType(); ct.emailID = emailID; ct.mobileNo = mobileNo; b.beneficiaryName = nm; b.beneficiaryAddress = ad; b.beneficiaryContact = ct; gTransfer.beneficiary = bt; gTransfer.beneficiary.Item = b; gTransfer.version = "2"; gTransfer.uniqueRequestNo = uniqueRequestNo; //Ihno gTransfer.appID = appID; gTransfer.customerID = customerID; gTransfer.debitAccountNo = debitAccountNo; gTransfer.transferAmount = transferAmount; //gTransfer.transferType = transferTypeType.IMPS; gTransfer.transferType = transferTypeType.IMPS; gTransfer.transferCurrencyCode = currencyCodeType.INR; gTransfer.remitterToBeneficiaryInfo = "FUND TRANSFER"; try { gTransferResponse = APIBanking.DomesticRemittanceClient.getTransfer(env, gTransfer); //return Request.CreateResponse(HttpStatusCode.OK, getBalanceResponse); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(gTransferResponse.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, gTransferResponse); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes.ToString()); c.InsertResponse(gTransferResponse.transactionStatus.subStatusCode, gTransferResponse.transactionStatus.statusCode.ToString(), gTransferResponse.requestReferenceNo, gTransferResponse.transactionStatus.bankReferenceNo); return(this.Request.CreateResponse(HttpStatusCode.OK, gTransferResponse)); } catch (FaultException ex) { String faultCode = ex.Code.SubCode.Name; String FaultReason = ex.Message; message = faultCode + " - " + FaultReason; HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", faultCode); myCustomError.Add("Errormsg", FaultReason); myCustomError.Add("Ihno", uniqueRequestNo); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); c.InsertResponse(faultCode, FaultReason, uniqueRequestNo, ""); c.writelog(ex.Message, "FaultException", DateTime.Now, "", ""); return(Request.CreateResponse(HttpStatusCode.ExpectationFailed, myCustomError)); } //catch (TimeoutException ex) //{ // message = ex.Message; // HttpError myCustomError = new HttpError(message); // // return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError); // //return this.Request.CreateResponse(HttpStatusCode.OK, gTransferResponse); //} //catch (CommunicationException ex) //{ // message = ex.Message; // HttpError myCustomError = new HttpError(message); // // return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError); // //return this.Request.CreateResponse(HttpStatusCode.OK, gTransferResponse); //} catch (Exception ex) { c.writelog(ex.Message, "TransferBal", DateTime.Now, "", ""); HttpError myCustomError = new HttpError(); myCustomError.Add("ErrorCode", 500); myCustomError.Add("Errormsg", "InternerlServer Error"); myCustomError.Add("Ihno", uniqueRequestNo); StringWriter sw = new StringWriter(); XmlTextWriter tw = null; XmlSerializer serializer = new XmlSerializer(myCustomError.GetType()); tw = new XmlTextWriter(sw); serializer.Serialize(tw, myCustomError); string tes = sw.ToString(); c.updatelogrequest(Convert.ToInt32(ds.Tables[0].Rows[0]["KMR_Slno"]), tes); c.InsertResponse("500", ex.Message, uniqueRequestNo, ""); c.writelog(ex.Message, "TransferBal", DateTime.Now, "", ""); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError)); } }