protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { // http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx var message = string.Format("No HTTP resource was found that matches the request URI '{0}'.", actionContext.Request.RequestUri); var error = new HttpError(message); actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, error); }
public void GetPropertyValue_GetsDefault_IfPropertyMissing() { HttpError error = new HttpError(); Assert.Null(error.GetPropertyValue<string>("key")); Assert.Equal(0, error.GetPropertyValue<int>("key")); }
public async override Task Invoke(IOwinContext context) { try { await Next.Invoke(context); } catch(Exception ex) { _logger.Error("Last chance exception caught.", ex); var headers = context.Request.Headers; // if server accepts json - just return json error if (headers.ContainsKey("Accept") && headers["Accept"].Contains("application/json")) { var includeDetail = context.Request.LocalIpAddress == context.Request.RemoteIpAddress; var message = new HttpError(ex, includeDetail); var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; context.Response.StatusCode = 500; context.Response.Write(JsonConvert.SerializeObject(message, serializerSettings)); } // otherwise - let the owin to return html else { throw; } } }
public HttpResponseMessage Get(string id) { try { TrataRetorno objRetorno = new TrataRetorno(); List<Indice> Indices = new List<Indice>(); string urlInicial = "http://finance.yahoo.com/webservice/v1/symbols/"; string urlFinal = "/quote?format=xml&view=detail"; string[] stringSeparators = new string[] { "," }; string[] result; result = id.Split(stringSeparators, StringSplitOptions.None); foreach (string s in result) { XPathDocument doc = new XPathDocument(urlInicial + s + urlFinal); Indices.Add(objRetorno.TratarRetorno(doc)); } return Request.CreateResponse(HttpStatusCode.OK, Indices); ; } catch (KeyNotFoundException) { string mensagem = string.Format("Não foi possível criptografar a entrada: ", id); HttpError error = new HttpError(mensagem); return Request.CreateResponse(HttpStatusCode.NotFound, error); } }
public HttpResponseMessage Delete(string idUser, string emailUser, string passwordUser, string userRegistration, string statusUser) { try { User user = new User(); DateTime now = DateTime.Now; #region Atribuir/valorizar modelo if (!String.IsNullOrWhiteSpace(idUser)) user.IdUser = Convert.ToInt32(idUser); user.RegistrationDateUser = now; if (!String.IsNullOrWhiteSpace(userRegistration)) user.ChangeUserUser = Convert.ToInt32(userRegistration); #endregion return Request.CreateResponse(HttpStatusCode.OK, user); ; } catch (KeyNotFoundException) { string mensagem = string.Format("Não foi possível criptografar a entrada: ", emailUser); HttpError error = new HttpError(mensagem); return Request.CreateResponse(HttpStatusCode.NotFound, error); } }
public HttpError ToHttpError(params object[] args) { var http = new HttpError(); http["Message"] = string.Format(Message, args); http["Type"] = Type; return http; }
// GET /api/projects/4/researchitems/5 public virtual HttpResponseMessage Get(int projectId, int researchItemId) { var researchItems = new List<ResearchItem>(); var project = new Project(); try { // Verify that the user is the owner of project and research item. project = _projectRepository.GetByUser(projectId, User.Identity.Name); if (project == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Project not found for user " + User.Identity.Name + "."); } var researchItem = _researchItemRepository.GetByUser(researchItemId, User.Identity.Name); if (researchItem == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Research item not found for user " + User.Identity.Name + "."); } researchItems.Add(researchItem); } catch (Exception ex) { var error = new HttpError("Error getting research item: " + ex.Message) { { "Trace", ex.StackTrace } }; return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } var researchItemDto = new ResearchItemDto() { Meta = new ResearchItemMeta() { NumberResearchItems = researchItems.Count(), ProjectName = project.Name }, ResearchItems = researchItems }; return Request.CreateResponse<ResearchItemDto>(HttpStatusCode.OK, researchItemDto); }
public override void OnException(HttpActionExecutedContext context) { if (context.Exception is FormValidationException) { var exception = context.Exception as FormValidationException; var fieldErrors = exception.FieldErrors .Select(x => "{ Field: " + x.Item1 + ", Error: " + x.Item2 + " }"); var error = new HttpError(exception.Message) { { "Type", "FormValidationException"}, { "FieldErrors", fieldErrors} }; context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } else if (context.Exception is DomainException) { var exception = context.Exception as DomainException; var error = new HttpError(exception.Message) { { "Type", "DomainException"}, }; context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } else { var error = new HttpError("An unknown error has occurred."); context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } }
// Convert the model state errors in to a string (for debugging only). // This should be improved once ODataError allows more details. private static string ConvertModelStateErrors(HttpError error) { StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<string, object> modelStateError in error) { if (modelStateError.Value != null) { builder.Append(modelStateError.Key); builder.Append(" : "); IEnumerable<string> errorMessages = modelStateError.Value as IEnumerable<string>; if (errorMessages != null) { foreach (string errorMessage in errorMessages) { builder.AppendLine(errorMessage); } } else { builder.AppendLine(modelStateError.Value.ToString()); } } } return builder.ToString(); }
public HttpResponseMessage Post(LogOnModel user) { try { Impersonate.ImpersonateUser(ConfigurationManager.AppSettings["Domain"].ToString(), user.UserName, user.Password); if (this.ValidateUser(user)) { FormsAuthentication.SetAuthCookie(user.UserName, true); return Request.CreateResponse(HttpStatusCode.OK, true); } return Request.CreateResponse(HttpStatusCode.OK, false); } catch (DirectoryServicesCOMException dse) { HttpError error = new HttpError(dse.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ")); return Request.CreateResponse(HttpStatusCode.Unauthorized, error); } catch (Exception) { throw; } finally { Impersonate.UndoImpersonation(); } }
public HttpResponseMessage Get(int id) { var periodDetialsRequestViewModel = new PeriodDetailsRequestViewModel() { PeriodId = id }; var serviceResponse = _periodDetailsPresenter.GetListingsByGroupId(periodDetialsRequestViewModel); HttpResponseMessage httpResponse; switch (serviceResponse.StatusCode) { case PeriodicTableStatusCodes.Success: httpResponse = Request.CreateResponse(HttpStatusCode.OK, serviceResponse); break; case PeriodicTableStatusCodes.Error: var internalServiceError = PeriodicTableServerExceptionResponse.GetInternalServiceError(); httpResponse = Request.CreateResponse(HttpStatusCode.InternalServerError, internalServiceError); break; default: var error = new HttpError(GetCorrectErrorMessage(serviceResponse.StatusCode)) { {"ErrorCode", serviceResponse.StatusCode} }; httpResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); break; } return httpResponse; }
public HttpResponseMessage Post(LogOnModel model) { try { if (this.ValidateUser(model)) { FormsAuthentication.SetAuthCookie(model.UserName,true); return Request.CreateResponse(HttpStatusCode.OK, true); } return Request.CreateResponse(HttpStatusCode.OK, false); } catch (DirectoryServicesCOMException dse) { HttpError error = new HttpError(dse.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ")); return Request.CreateResponse(HttpStatusCode.Unauthorized, error); } catch (Exception ex) { HttpError error = new HttpError(ex.Message.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ")); EventLog log = new EventLog(); log.Source = "Jaguar_Mobile"; log.WriteEntry(ex.Message); return Request.CreateResponse(HttpStatusCode.InternalServerError, error); } }
private static ODataInnerError ToODataInnerError(HttpError httpError) { string innerErrorMessage = httpError.GetPropertyValue<string>(HttpErrorKeys.ExceptionMessageKey); if (innerErrorMessage == null) { string messageDetail = httpError.GetPropertyValue<string>(HttpErrorKeys.MessageDetailKey); if (messageDetail == null) { HttpError modelStateError = httpError.GetPropertyValue<HttpError>(HttpErrorKeys.ModelStateKey); return (modelStateError == null) ? null : new ODataInnerError { Message = ConvertModelStateErrors(modelStateError) }; } else { return new ODataInnerError() { Message = messageDetail }; } } else { ODataInnerError innerError = new ODataInnerError(); innerError.Message = innerErrorMessage; innerError.TypeName = httpError.GetPropertyValue<string>(HttpErrorKeys.ExceptionTypeKey); innerError.StackTrace = httpError.GetPropertyValue<string>(HttpErrorKeys.StackTraceKey); HttpError innerExceptionError = httpError.GetPropertyValue<HttpError>(HttpErrorKeys.InnerExceptionKey); if (innerExceptionError != null) { innerError.InnerError = ToODataInnerError(innerExceptionError); } return innerError; } }
public void SerializeError_serializes_httperror() { using (var stream = new MemoryStream()) { var textWriter = new StreamWriter(stream); var writer = new JsonTextWriter(textWriter); var mockInnerException = new Mock<Exception>(MockBehavior.Strict); mockInnerException.Setup(m => m.Message).Returns("Inner exception message"); mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace"); var outerException = new Exception("Outer exception message", mockInnerException.Object); var error = new HttpError(outerException, true) { StackTrace = "Outer stack trace" }; var jsonSerializer = new JsonSerializer(); var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict); mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID"); var serializer = new ErrorSerializer(mockIdProvider.Object); serializer.SerializeError(error, stream, writer, jsonSerializer); writer.Flush(); var expectedJson = File.ReadAllText("ErrorSerializerTest.json"); var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson); var output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); output.Should().Be(minifiedExpectedJson); } }
// POST api/projects (Insert) public override HttpResponseMessage Post(Project project) { // Check for presence of V2 "IsUrgent" flag. if (project.IsUrgent == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The IsUrgent indicator is required."); } try { project.UserName = User.Identity.Name; project.DateCreated = DateTime.Now; project.DateUpdated = DateTime.Now; _projectRepository.Insert(project); _projectRepository.Commit(); } catch (Exception ex) { var error = new HttpError("Error inserting project: " + ex.Message) { { "Trace", ex.StackTrace } }; return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } var response = Request.CreateResponse(HttpStatusCode.Created, project); string uri = Url.Link("DefaultApi", new { id = project.ProjectId }); response.Headers.Location = new Uri(uri); return response; }
/// <summary> /// GET: api/Widget/{title}. Return search results. Empty string gives zero length result. /// </summary> public HttpResponseMessage Get(string title) { var bvms = new List<BookViewModel>(); //var results = new List<KeyValuePair<string, List<string>>>(); // Title, authors var results = new List<WidgetResponseRow>(); if (title != "") { try { bvms = BookServices.SearchBooks(title); foreach (var bvm in bvms) { results.Add(new WidgetResponseRow(bvm.ISBN, bvm.Title, bvm.Authors.Select(i => i.Value).ToList())); } } catch (DataAccessException) { var error = new HttpError("Data access error."); return Request.CreateResponse(HttpStatusCode.InternalServerError, error); } } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, results); response.ReasonPhrase = "OK"; return response; }
// PUT api/projects/5 (Update) public override HttpResponseMessage Put(int id, Project project) { // Check for presence of V2 "IsUrgent" flag. if (project.IsUrgent == null) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The IsUrgent indicator is required."); } var currentProject = new Project(); try { // Verify that the user is the owner currentProject = _projectRepository.GetByUser(id, User.Identity.Name); if (currentProject == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Project not found for user " + User.Identity.Name + "."); } currentProject.DateUpdated = DateTime.Now; currentProject.Name = project.Name; currentProject.Description = project.Description; currentProject.IsUrgent = project.IsUrgent; _projectRepository.Commit(); } catch (Exception ex) { var error = new HttpError("Error updating project: " + ex.Message) { { "Trace", ex.StackTrace } }; return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error); } var response = Request.CreateResponse(HttpStatusCode.OK, currentProject); string uri = Url.Link("DefaultApi", new { id = id }); response.Headers.Location = new Uri(uri); return response; }
private string GenerateErrorKey(HttpError httpError) { var guid = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false) .Select(a => ((System.Runtime.InteropServices.GuidAttribute)a).Value) .FirstOrDefault(); return ""; }
public void WriteObject_SupportsHttpError() { var serializer = new ODataErrorSerializer(); var error = new HttpError("bad stuff"); Mock<IODataResponseMessage> mockResponseMessage = new Mock<IODataResponseMessage>(); mockResponseMessage.Setup(response => response.GetStream()).Returns(new MemoryStream()); Assert.DoesNotThrow(() => serializer.WriteObject(error, new ODataMessageWriter(mockResponseMessage.Object), new ODataSerializerContext())); }
public HttpServiceError(ServiceException exception, bool includeErrorDetail = false) { if (exception == null) { throw new ArgumentNullException("exception"); } _includeErrorDetail = includeErrorDetail; _httpError = Populate((dynamic) exception, out _statusCode); }
/// <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 ); } }
public HttpResponseMessage Get(string idBook, string initialsBook, string amountChapterBook, string amountVerseBook, string idVersionBook, string nameFile, string versionDownload) { try { List<Verse> listVerse = new List<Verse>(); Verse verse; int count = 0; if (!String.IsNullOrWhiteSpace(amountChapterBook)) { for (int countAmountChapterBook = 1; countAmountChapterBook <= Convert.ToInt32(amountChapterBook); countAmountChapterBook++) { int countAmountVerseBook = 0; string xpath = ""; HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load("https://www.bibliaonline.com.br/"+ versionDownload + "/" + initialsBook + "/" + countAmountChapterBook); var output = doc.DocumentNode.SelectNodes("//div[@id='ChapterView']//span"); HtmlWeb web2 = new HtmlWeb(); HtmlAgilityPack.HtmlDocument htmldoc = web2.Load("https://www.bibliaonline.com.br/" + versionDownload + "/" + initialsBook + "/" + countAmountChapterBook); htmldoc.OptionFixNestedTags = true; var navigator = (HtmlNodeNavigator)htmldoc.CreateNavigator(); foreach (var item in output) { verse = new Verse(); count++; countAmountVerseBook++; xpath = "/html[1]/body[1]/div[1]/div[1]/div[2]/div[1]/article[1]/div[1]/p[" + countAmountVerseBook + "]/span[1]"; verse.Id = count; verse.IdBook = Convert.ToInt32(idBook); verse.IdChapter = countAmountChapterBook; verse.IdVerse = countAmountVerseBook; verse.TextVerse = navigator.SelectSingleNode(xpath).Value; listVerse.Add(verse); } countAmountVerseBook = 0; } } var json = JsonConvert.SerializeObject(listVerse); var result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new StringContent(json, Encoding.UTF8, "application/json"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = initialsBook+nameFile+".json" }; return result; } catch (KeyNotFoundException) { string mensagem = string.Format("Não foi possível Capturar o livro: " + initialsBook); HttpError error = new HttpError(mensagem); return Request.CreateResponse(HttpStatusCode.NotFound, 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 void ExceptionConstructorWithoutDetail_AddsCorrectDictionaryItems() { HttpError error = new HttpError(new ArgumentException("error", new Exception()), false); Assert.Contains(new KeyValuePair<string, object>("Message", "An error has occurred."), error); Assert.False(error.ContainsKey("ExceptionMessage")); Assert.False(error.ContainsKey("ExceptionType")); Assert.False(error.ContainsKey("StackTrace")); Assert.False(error.ContainsKey("InnerException")); }
private HttpError Populate(ServiceException exception, out HttpStatusCode statusCode) { var httpError = new HttpError(exception, _includeErrorDetail) { {"ErrorType", "service"} }; httpError.Message = exception.Message; statusCode = HttpStatusCode.InternalServerError; return httpError; }
private HttpError Populate(ValidationException exception, out HttpStatusCode statusCode) { var httpError = new HttpError(exception, _includeErrorDetail) { { "ErrorType", "validation" }, { "Faults", exception.Faults } }; httpError.Message = exception.Message; statusCode = HttpStatusCode.BadRequest; return httpError; }
private static object ResolveExceptionDto(HttpError error) { if (error == null) return null; dynamic r = new ExpandoObject(); r.type = error.ExceptionType; r.message = error.ExceptionMessage; r.stackTrace = from line in error.StackTrace.Split(new[] {Environment.NewLine}, StringSplitOptions.None) select line.Trim(); r.innerException = ResolveExceptionDto(error.InnerException); return r; }
private static string GetRecursiveExceptionMessage(HttpError ex) { var msg = !string.IsNullOrEmpty(ex.ExceptionMessage) ? ex.ExceptionMessage : ex.Message; msg = msg?.EnsureEndsWith("."); if (ex.InnerException != null) { msg += ' ' + GetRecursiveExceptionMessage(ex.InnerException); } return msg; }
public JsonApiError(HttpError error, IErrorIdProvider idProvider) { Id = idProvider.GenerateId(error); Title = error.ExceptionType ?? error.Message; Status = "500"; Detail = error.ExceptionMessage ?? error.MessageDetail; StackTrace = error.StackTrace; if (error.InnerException != null) Inner = new JsonApiError(error.InnerException, idProvider); }
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); }
public override object OnDelete(PedidoItem request) { try{ var factory = Factory; factory.Execute(proxy => { var pedido = proxy.FirstOrDefaultById <Pedido>(request.IdPedido); if (pedido == default(Pedido)) { throw HttpError.NotFound(string.Format("Item no puede ser borrado. No existe Pedido con Id: '{0}'", request.IdPedido)); } if (pedido.FechaEnvio.HasValue) { throw HttpError.Unauthorized(string.Format("Item no puede ser borrado. Pedido '{0}' Id:'{1} No puede ser Actualizado. Estado:Enviado ", pedido.Consecutivo, pedido.Id)); } if (pedido.FechaAnulado.HasValue) { throw HttpError.Unauthorized(string.Format("Item no puede ser borrado. Pedido '{0}' Id:'{1} No puede ser Actualizado. Estado:Anulado ", pedido.Consecutivo, pedido.Id)); } proxy.Delete <PedidoItem>(q => q.Id == request.Id); }); List <PedidoItem> data = new List <PedidoItem>(); data.Add(request); return(new Response <PedidoItem>() { Data = data }); } catch (Exception e) { return(HttpResponse.ErrorResult <Response <PedidoItem> >(e, "DeletePedidoItemError")); } }
// PUT /api/projects/4/researchitems/5 public virtual HttpResponseMessage Put(int projectId, int researchItemId, ResearchItem researchItem) { var project = new Project(); ResearchItem currentResearchItem = null; try { project = _projectRepository.GetByUser(projectId, User.Identity.Name); if (project == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Project not found for user " + User.Identity.Name + ".")); } currentResearchItem = _researchItemRepository.GetByUser(researchItemId, User.Identity.Name); if (currentResearchItem == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Research item not found for user " + User.Identity.Name + ".")); } currentResearchItem.DateUpdated = DateTime.Now; currentResearchItem.Subject = researchItem.Subject; currentResearchItem.Description = researchItem.Description; _researchItemRepository.Commit(); } catch (Exception ex) { var error = new HttpError("Error updating research item: " + ex.Message) { { "Trace", ex.StackTrace } }; return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error)); } var response = Request.CreateResponse(HttpStatusCode.OK, currentResearchItem); string uri = Url.Link("ProjectResearchItemsApi", new { projectId = projectId, researchItemId = researchItem.ResearchItemId }); response.Headers.Location = new Uri(uri); return(response); }
public HttpResponseMessage DeleteAll() { try { PregnancyEntity connect = new PregnancyEntity(); int user_id = Convert.ToInt32(((ClaimsIdentity)(User.Identity)).FindFirst("id").Value); IQueryable <preg_user_kick_history> items = dao.GetListItem().Where(c => c.user_id == user_id); if (!items.Any()) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, SysConst.DATA_NOT_FOUND)); } while (items.Count() > 0) { int kickResultId = items.FirstOrDefault().kick_result_id; IQueryable <preg_kick_result_detail> kickResultDetailItem = connect.preg_kick_result_detail.Where(c => c.kick_result_id == kickResultId); while (kickResultDetailItem.Count() > 0) { connect.preg_kick_result_detail.Remove(kickResultDetailItem.FirstOrDefault()); connect.SaveChanges(); } dao.DeleteData(items.FirstOrDefault()); IQueryable <preg_kick_result> kickResultItem = connect.preg_kick_result.Where(c => c.id == kickResultId); while (kickResultItem.Count() > 0) { connect.preg_kick_result.Remove(kickResultItem.FirstOrDefault()); connect.SaveChanges(); } } return(Request.CreateResponse(HttpStatusCode.Accepted, SysConst.DATA_DELETE_SUCCESS)); } catch (Exception ex) { HttpError err = new HttpError(ex.Message); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, err)); } }
public HttpResponseMessage Get([FromUri] preg_question_type data) { try { if (!data.DeepEquals(new preg_question_type())) { IEnumerable <preg_question_type> result = dao.GetItemsByParams(data); if (result.Count() > 0) { return(Request.CreateResponse(HttpStatusCode.OK, result)); } else { HttpError err = new HttpError(SysConst.DATA_NOT_FOUND); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, err)); } } else { IEnumerable <preg_question_type> result = dao.GetListItem(); if (result.Count() > 0) { return(Request.CreateResponse(HttpStatusCode.OK, result)); } else { HttpError err = new HttpError(SysConst.DATA_NOT_FOUND); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, err)); } } } catch (Exception ex) { HttpError err = new HttpError(ex.Message); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, err)); } }
private static ODataInnerError ToODataInnerError(HttpError httpError) { string innerErrorMessage = httpError.GetPropertyValue <string>(HttpErrorKeys.ExceptionMessageKey); if (innerErrorMessage == null) { string messageDetail = httpError.GetPropertyValue <string>(HttpErrorKeys.MessageDetailKey); if (messageDetail == null) { HttpError modelStateError = httpError.GetPropertyValue <HttpError>(HttpErrorKeys.ModelStateKey); return((modelStateError == null) ? null : new ODataInnerError { Message = ConvertModelStateErrors(modelStateError) }); } else { return(new ODataInnerError() { Message = messageDetail }); } } else { ODataInnerError innerError = new ODataInnerError(); innerError.Message = innerErrorMessage; innerError.TypeName = httpError.GetPropertyValue <string>(HttpErrorKeys.ExceptionTypeKey); innerError.StackTrace = httpError.GetPropertyValue <string>(HttpErrorKeys.StackTraceKey); HttpError innerExceptionError = httpError.GetPropertyValue <HttpError>(HttpErrorKeys.InnerExceptionKey); if (innerExceptionError != null) { innerError.InnerError = ToODataInnerError(innerExceptionError); } return(innerError); } }
protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password, string referrerUrl) { if (!LoginMatchesSession(session, userName)) { authService.RemoveSession(); session = authService.GetSession(); } if (TryAuthenticate(authService, userName, password)) { session.IsAuthenticated = true; if (session.UserAuthName == null) { session.UserAuthName = userName; } var response = OnAuthenticated(authService, session, null, null); if (response != null) { return(response); } return(new AuthenticateResponse { UserId = session.UserAuthId, UserName = userName, SessionId = session.Id, DisplayName = session.DisplayName ?? session.UserName ?? "{0} {1}".Fmt(session.FirstName, session.LastName).Trim(), ReferrerUrl = referrerUrl }); } throw HttpError.Unauthorized(ErrorMessages.InvalidUsernameOrPassword); }
public void TranslateHttpResponseException_Unpacks_HttpError_With_No_Fields_Set() { // Arrange HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri("http://localhost"), Method = HttpMethod.Get }; Exception exception = null; try { throw new InvalidOperationException("ExpectedExceptionMessage"); } catch (Exception ex) { exception = ex; } HttpError httpError = new HttpError(); HttpResponseMessage errorResponse = request.CreateResponse(HttpStatusCode.BadRequest); errorResponse.Content = new ObjectContent <HttpError>(httpError, new JsonMediaTypeFormatter()); TraceRecord traceRecord = new TraceRecord(request, "System.Web.Http.Request", TraceLevel.Error) { Exception = new HttpResponseException(errorResponse) }; // Act new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord); // Assert Assert.Equal(TraceLevel.Warn, traceRecord.Level); Assert.Equal(string.Empty, traceRecord.Message); }
public override Task ExecuteBindingAsync( ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { if (actionContext.Request.Headers.TryGetValues(_name, out var values)) { try { actionContext.ActionArguments[Descriptor.ParameterName] = values.FirstOrDefault(); } catch (Exception exception) { var error = new HttpError("The request is invalid.") { MessageDetail = exception.Message }; throw new HttpResponseException( actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error)); } } else if (Descriptor.IsOptional) { actionContext.ActionArguments[Descriptor.ParameterName] = Descriptor.DefaultValue ?? ""; } else { var error = new HttpError("The request is invalid.") { MessageDetail = $"The `{_name}` header is required." }; throw new HttpResponseException( actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error)); } return(Task.CompletedTask); }
public HttpResponseMessage GetCustomer(string customerID = null) { HttpResponseMessage retObject = null; bool IsError = false; Customer customer = null; var message = ""; if (string.IsNullOrEmpty(customerID)) { message = string.Format("Customer ID is empty or null"); HttpError err = new HttpError(message); retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err); retObject.ReasonPhrase = message; IsError = true; } else { customer = repository.Get(customerID); if (customer.CustomerID == null) { message = string.Format("Customer with id [{0}] not found", customerID); HttpError err = new HttpError(message); retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err); retObject.ReasonPhrase = message; IsError = true; } } if (IsError) { return(retObject); } else { return(Request.CreateResponse(HttpStatusCode.OK, customer)); } }
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; }
// POST api/projects (Insert) public virtual HttpResponseMessage Post(Project project) { try { project.UserName = User.Identity.Name; project.DateCreated = DateTime.Now; project.DateUpdated = DateTime.Now; _projectRepository.Insert(project); _projectRepository.Commit(); } catch (Exception ex) { var error = new HttpError("Error inserting project: " + ex.Message) { { "Trace", ex.StackTrace } }; return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error)); } var response = Request.CreateResponse(HttpStatusCode.Created, project); string uri = Url.Link("DefaultApi", new { id = project.ProjectId }); response.Headers.Location = new Uri(uri); return(response); }
public override void Handle(ExceptionHandlerContext context) { var exception = context.ExceptionContext.Exception.GetException(); var errorType = 1; switch (exception) { case SqlException _: var ex = exception as SqlException; //this is custom validation message thrown from sql server if (ex?.Number == 60000) { errorType = 2; } break; case BusinessException _: errorType = 2; break; case UnAuthorizedException _: errorType = 3; break; } context.Request.Properties.TryGetValue("uel:error_code", out var logID); var error = new HttpError { { "errorType", errorType }, { "code", logID }, { "message", exception.Message } }; var response = context.Request.CreateErrorResponse(System.Net.HttpStatusCode.InternalServerError, error); response.ReasonPhrase = exception.GetType().FullName; context.Result = new ResponseMessageResult(response); }
public object Get(GetProduct request) { if (Request.Headers["Authorization"] == null || !JsonWebToken.Decode(Request.Headers["Authorization"], iuserservice)) { return(new HttpError(HttpStatusCode.Forbidden, "Invalid token")); } if (request.Id?.Length != 24) { return(new HttpError(HttpStatusCode.BadRequest, "Bad Request")); } var result = iproductservice.GetProductById(request.Id); if (!string.IsNullOrEmpty(result.Message)) { return(StatusCode(result)); } if (result.Entity == null) { return(HttpError.NotFound("Not Found")); } return(result.Entity); }
public HttpResponseMessage Put(string id, [FromBody] preg_kick_result dataUpdate) { try { if (!dataUpdate.DeepEquals(new preg_kick_result())) { preg_kick_result kick_result = new preg_kick_result(); kick_result = dao.GetItemByID(Convert.ToInt32(id)).FirstOrDefault(); if (kick_result == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, SysConst.DATA_NOT_FOUND)); } if (dataUpdate.kick_date != null) { kick_result.kick_date = dataUpdate.kick_date; } if (dataUpdate.duration != null) { kick_result.duration = dataUpdate.duration; } dao.UpdateData(kick_result); return(Request.CreateResponse(HttpStatusCode.Accepted, SysConst.DATA_UPDATE_SUCCESS)); } else { HttpError err = new HttpError(SysConst.DATA_NOT_EMPTY); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, err)); } } catch (Exception ex) { HttpError err = new HttpError(ex.Message); return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, err)); } }
public HttpResponseMessage Delete(int actividadID) { try { var result = this._DeleteActividad(actividadID); return(Request.CreateResponse <bool>(HttpStatusCode.OK, result)); } catch (SqlException ex) { HttpError err = new HttpError("No se puede eliminar esta actividad, algunos registros podrían quedar huérfanos."); if (ex.Message.Contains("FK_")) { return(Request.CreateResponse(HttpStatusCode.Conflict, err)); } //throw new HttpResponseException(HttpStatusCode.Conflict); err = new HttpError("Error no controlado."); return(Request.CreateResponse(HttpStatusCode.Conflict, err)); } catch (Exception ex) { HttpError err = new HttpError(ex.Message); return(Request.CreateResponse(HttpStatusCode.Conflict, err)); } }
/// <summary> /// Logic to update UserAuth from Registration info, not enabled on PUT because of security. /// </summary> public async Task <object> UpdateUserAuthAsync(Register request) { if (!HostContext.AppHost.GlobalRequestFiltersAsyncArray.Contains(ValidationFilters.RequestFilterAsync)) //Already gets run { await RegistrationValidator.ValidateAndThrowAsync(request, ApplyTo.Put).ConfigAwait(); } var response = ValidateFn?.Invoke(this, HttpMethods.Put, request); if (response != null) { return(response); } var session = await this.GetSessionAsync().ConfigAwait(); var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(base.Request); await using (authRepo as IAsyncDisposable) { var existingUser = await authRepo.GetUserAuthAsync(session, null).ConfigAwait(); if (existingUser == null) { throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request)); } var newUserAuth = ToUser(request); await authRepo.UpdateUserAuthAsync(existingUser, newUserAuth, request.Password).ConfigAwait(); return(new RegisterResponse { UserId = existingUser.Id.ToString(CultureInfo.InvariantCulture), }); } }
static HttpError CreateODataError(ErrorResponseContext context) { Contract.Requires(context != null); Contract.Ensures(Contract.Result <HttpError>() != null); var error = new HttpError(); if (!IsNullOrEmpty(context.Code)) { error[HttpErrorKeys.ErrorCodeKey] = context.Code; } if (!IsNullOrEmpty(context.Message)) { error.Message = context.Message; } if (!IsNullOrEmpty(context.MessageDetail) && context.Request.ShouldIncludeErrorDetail() == true) { error[HttpErrorKeys.MessageDetailKey] = context.MessageDetail; } return(error); }
public async Task HttpError_Roundtrips_WithJsonFormatter() { HttpError error = new HttpError("error") { { "ErrorCode", 42 }, { "Data", new[] { "a", "b", "c" } } }; MediaTypeFormatter formatter = new JsonMediaTypeFormatter(); MemoryStream stream = new MemoryStream(); await formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content : null, transportContext : null); stream.Position = 0; HttpError roundtrippedError = (await formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null)) as HttpError; Assert.NotNull(roundtrippedError); Assert.Equal("error", roundtrippedError.Message); Assert.Equal(42L, roundtrippedError["ErrorCode"]); JArray data = roundtrippedError["Data"] as JArray; Assert.Equal(3, data.Count); Assert.Contains("a", data); Assert.Contains("b", data); Assert.Contains("c", data); }
public object Get(KeyRequest key) { if (string.Equals(key.Key, "all", StringComparison.InvariantCultureIgnoreCase)) { return(AppSettings.GetAllKeys()); } var result = AppSettings.GetString(key.Key); var recurse = AppSettings.GetString("testKey"); var exists = AppSettings.Exists(key.Key); // True var existsno = AppSettings.Exists($"no{key.Key}"); // False var list = AppSettings.GetList($"{key.Key}List"); // default var listno = AppSettings.GetList($"no{key.Key}List"); // not found var dict = AppSettings.GetDictionary($"{key.Key}Dict"); // service specifc var dictno = AppSettings.GetDictionary($"no{key.Key}Dict"); // not found var str = AppSettings.GetString($"{key.Key}Str"); // version specific "version-specific" var strno = AppSettings.GetString($"no{key.Key}Str"); // not found var instance = AppSettings.GetString($"{key.Key}ii"); // version specific "instance-specific" var strLower = AppSettings.GetString($"{key.Key}Str/lower"); // default "extra" var strLowerno = AppSettings.GetString($"no{key.Key}Str/lower"); // not found var type = AppSettings.Get <KeyRequest>($"{key.Key}request"); // default var typeno = AppSettings.Get <KeyRequest>($"no{key.Key}request"); // not found var typedef = AppSettings.Get($"no{key.Key}request", new KeyRequest { Body = "Chirpy cheep", Key = "Fallback value" }); // not found, returns fallback throw HttpError.NotFound($"Could not find config value with key {key.Key}"); }
public async Task Update(string commentId, string id, UpdateResponseDto dto) { User user = await _sessionService.GetUser(); Validate("modify", dto.Content, user); Response response = await _responseRepository.GetById(id); if (response == null) { _logger.LogWarning($"Response {id} does not exist"); throw HttpError.NotFound($"Response {id} does not exist"); } if (response.CommentId != commentId) { throw HttpError.NotFound(""); } if (response.AuthorId != user.Id) { _logger.LogWarning($"Response {id} does not belong to user"); throw HttpError.Forbidden($"Response {id} does not belong to user"); } response.Content = dto.Content; response.LastUpdateTime = DateTime.Now; bool success = await _responseRepository.Update(response); if (!success) { _logger.LogWarning("Error during update response"); throw HttpError.InternalServerError(""); } }
public HttpResponseMessage Get(string username) { try { var user = Membership.GetUser(username); if (user == null) { var httpError = new HttpError(string.Format("The username '{0}' does not exist.", username)); _logger.Debug(httpError.Message); httpError["error_sub_code"] = 1003; return(Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError)); } return(Request.CreateResponse(HttpStatusCode.OK, Map(user))); } catch (Exception ex) { var message = string.Format("Cannot retrieve user by username '{0}'.", username); _logger.DebugException(message, ex); var httpError = new HttpError(message); httpError["error_sub_code"] = 1010; httpError["error"] = ex.Message; return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError)); } }
public async Task <object> Any(StoreFileUpload request) { var feature = AssertPlugin <FilesUploadFeature>(); var location = feature.AssertLocation(request.Name, Request); if (Request.Files.Length == 0) { throw HttpError.BadRequest("No files uploaded"); } var session = await Request.GetSessionAsync(); var results = new List <string>(); foreach (var file in Request.Files) { var path = await feature.UploadFileAsync(location, Request, session, file).ConfigAwait(); results.Add(path); } return(new StoreFileUploadResponse { Results = results, }); }
public void SerializeErrorIntegrationTest() { // Arrange JsonApiFormatter formatter = new JSONAPI.Json.JsonApiFormatter(new JSONAPI.Core.PluralizationService()); MemoryStream stream = new MemoryStream(); // Act var payload = new HttpError(new Exception("This is the exception message!"), true) { StackTrace = "Stack trace would go here" }; formatter.WriteToStreamAsync(typeof(HttpError), payload, stream, (System.Net.Http.HttpContent)null, (System.Net.TransportContext)null); // Assert var expectedJson = File.ReadAllText("ErrorSerializerTest.json"); var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson); var output = System.Text.Encoding.ASCII.GetString(stream.ToArray()); output = Regex.Replace(output, @"[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}", "TEST-ERROR-ID"); // We don't know what the GUID will be, so replace it output.Should().Be(minifiedExpectedJson); }
public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response; if (_data != null && _data.Any() && !_data.Contains(null)) { var apiData = new ApiResultData <T> { Count = _data.Count(), RetrivalDate = DateTime.UtcNow, Version = "v1", Results = _data }; response = _request.CreateResponse(HttpStatusCode.OK, apiData); } else { var httpErr = new HttpError(); httpErr["message"] = "No Sessions were found that meet your criteria"; response = _request.CreateErrorResponse(HttpStatusCode.NotFound, httpErr); } return(Task.FromResult(response)); }
public object Get(GetTechnology request) { int id; var tech = int.TryParse(request.Slug, out id) ? Db.SingleById <Technology>(id) : Db.Single <Technology>(x => x.Slug == request.Slug.ToLower()); if (tech == null) { throw HttpError.NotFound("Tech stack not found"); } var techStacks = Db.Select(Db.From <TechnologyStack>() .Join <TechnologyChoice>() .Join <TechnologyChoice, Technology>() .Where <TechnologyChoice>(x => x.TechnologyId == tech.Id) .OrderByDescending(x => x.LastModified)); return(new GetTechnologyResponse { Technology = tech, TechnologyStacks = techStacks }); }
//POST: criar uma sala /* Coordenadas e Limites de Musicas/Horas sao opcionais */ public HttpResponseMessage PostCriar(SalaCriacaoModel model) { ErrorReader errorReader = new ErrorReader(); if (Math.Abs(model.Xcoord) > 90 || Math.Abs(model.Ycoord) > 180) { var message = string.Format(errorReader.GetErrorMessage(0)); HttpError err = new HttpError(message); return(Request.CreateResponse(errorReader.GetError(0), err)); } else { if (model.Nome.Equals("") || model.Password.Equals("")) { var message = string.Format(errorReader.GetErrorMessage(8)); HttpError err = new HttpError(message); return(Request.CreateResponse(errorReader.GetError(8), err)); } else { SalaAccess sala = new SalaAccess(); SalaCriarModel smodel = new SalaCriarModel(); smodel.UserId = RequestContext.Principal.Identity.GetUserId(); smodel.Nome = model.Nome; smodel.Password = model.Password; smodel.Xcoord = model.Xcoord; smodel.Ycoord = model.Ycoord; smodel.LimiteMusicas = model.LimiteMusicas; smodel.LimiteHorario = model.LimiteHorario; return(Request.CreateResponse(HttpStatusCode.OK, sala.CriaSala(smodel))); } } }
public object Post(AssignRoles request) { RequiredRoleAttribute.AssertRequiredRoles(Request, RoleNames.Admin); if (string.IsNullOrEmpty(request.UserName)) { throw new ArgumentNullException(nameof(request.UserName)); } var userAuth = AuthRepository.GetUserAuthByUserName(request.UserName); if (userAuth == null) { throw HttpError.NotFound(request.UserName); } AuthRepository.AssignRoles(userAuth, request.Roles, request.Permissions); return(new AssignRolesResponse { AllRoles = AuthRepository.GetRoles(userAuth).ToList(), AllPermissions = AuthRepository.GetPermissions(userAuth).ToList(), }); }
public HttpResponseMessage Delete(string carId) { var response = ""; string ownerId = carBusiness.GetCar(carId).CarOwner.User_ID; if (!isUserIdEqualToLoggedInUser(ownerId)) { var message = string.Format("Permission denied"); HttpError err = new HttpError(message); return(Request.CreateResponse(HttpStatusCode.Unauthorized, err)); } else { if (carBusiness.CarIdExists(carId)) { bool carDeleted = carBusiness.DeleteCar(carId); if (carDeleted) { response = string.Format("Car unregistered successfully!"); return(Request.CreateResponse(HttpStatusCode.OK, string.Format(response))); } else { response = string.Format("Car not found"); HttpError err = new HttpError(response); return(Request.CreateResponse(HttpStatusCode.NotFound, err)); } } else { response = string.Format("Car not found"); HttpError err = new HttpError(response); return(Request.CreateResponse(HttpStatusCode.NotFound, err)); } } }
public HttpResponseMessage GetTemplate(string month) { try { IEnumerable <preg_my_belly> data = dao.GetItemsByParams(new preg_my_belly() { month = Convert.ToInt32(month) }).Where(c => c.user_id == null); if (data.Count() > 0) { return(Request.CreateResponse(HttpStatusCode.OK, data)); } else { HttpError err = new HttpError(SysConst.DATA_NOT_FOUND); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, err)); } } catch (Exception ex) { HttpError err = new HttpError(ex.Message); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, err)); } }
public async Task Update(string postId, string id, UpdateCommentDto dto) { User user = await _sessionService.GetUser(); Validate("modify", dto.Content, user); Comment comment = await _commentRepository.GetById(id); if (comment == null) { _logger.LogWarning($"Comment {id} does not exist"); throw HttpError.NotFound($"Comment {id} does not exist"); } if (comment.PostId != postId) { throw HttpError.NotFound(""); } if (comment.AuthorId != user.Id) { _logger.LogWarning($"Comment {id} does not belong to user"); throw HttpError.Forbidden($"Comment {id} does not belong to user"); } comment.Content = dto.Content; comment.LastUpdateTime = DateTime.Now; bool success = await _commentRepository.Update(comment); if (!success) { _logger.LogWarning("Error during update comment"); throw HttpError.InternalServerError(""); } }