public void Given_Values_When_Implicitly_Converted_Then_It_Should_Return_Result(string upn, InterfaceType @interface, string message, HttpStatusCode statusCode) { var correlationId = Guid.NewGuid(); var spanId = Guid.NewGuid(); var eventId = Guid.NewGuid(); var error = new ErrorObjectResult() { Upn = upn, CorrelationId = correlationId, Interface = @interface, SpanId = spanId, EventId = eventId, Message = message, StatusCode = (int)statusCode, }; ObjectResult result = error; result.Should().NotBeNull(); result.Value.Should().BeOfType <ErrorResponseMessage>(); (result.Value as ErrorResponseMessage).Upn.Should().Be(upn); (result.Value as ErrorResponseMessage).CorrelationId.Should().Be(correlationId); (result.Value as ErrorResponseMessage).Interface.Should().Be(@interface); (result.Value as ErrorResponseMessage).SpanId.Should().Be(spanId); (result.Value as ErrorResponseMessage).EventId.Should().Be(eventId); (result.Value as ErrorResponseMessage).Message.Should().Be(message); result.StatusCode.Should().Be((int)statusCode); }
public ErrorObjectResult Error(Error payload, string message = null) { Response.Headers.Add("x-api-standard", "1"); var err = new ErrorObjectResult( WrapError(payload, message != null ? message : payload.Message)); err.StatusCode = payload.StatusCode; return(err); }
public async Task <IActionResult> CriarQuestaoObjetiva([FromBody] CriarQuestaoObjetivaComando comando) { var(_, isFailure, questaoId, error) = await _mediator.Send(comando, new CancellationToken()); if (isFailure) { return(BadRequest(ErrorObjectResult.Criar("Não foi possível criar a questão", error))); } return(Ok(new { Id = questaoId })); }
public void BuildsErrorWithInternalServerErrorAndSpecifiedObjectTest() { var error = new { Code = 123, Message = Guid.NewGuid().ToString() }; var sut = new ErrorObjectResult(error); sut.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError); sut.Value.Should().Be(error); }
/// <summary> /// Creates an <see cref="HttpException" /> that produces an Error (500) response. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="error">The error to be returned to the client.</param> public static HttpException Error(this HttpResponse response, object error) { var disposable = error as IDisposable; if (disposable != null) { response.RegisterForDispose(disposable); } var result = new ErrorObjectResult(error); return(new HttpException(result)); }
public void BuildsErrorWithSpecifiedObjectAndStatusCodeTest() { var error = new { Code = 123, Message = Guid.NewGuid().ToString() }; var statusCode = HttpStatusCode.BadRequest; var sut = new ErrorObjectResult(error, statusCode); sut.StatusCode.Should().Be((int)statusCode); sut.Value.Should().Be(error); }
public void CreatesWithShieldMessageWhenNoMessageProvidedTest(string message) { var sut = new ErrorObjectResult(message); sut.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError); var value = sut.Value; // The internal value is a dynamic object so we need to provide a workaround to get access to the value via Reflection // Hacky, but acceptable for testing var actual = value.GetType().GetTypeInfo().GetProperty("Message", typeof(string)).GetValue(value) as string; actual.Should().NotBeNullOrWhiteSpace(); }
/// <summary> /// Gets the <see cref="ObjectResult"/> object from the list of <see cref="ExerciseEntity"/> objects. /// </summary> /// <param name="entities">List of <see cref="ExerciseEntity"/> objects.</param> /// <param name="request"><see cref="PublishRequestMessage"/> object.</param> /// <param name="eventId">Event ID.</param> /// <param name="httpStatusCode"><see cref="HttpStatusCode"/> value.</param> /// <returns>Returns the <see cref="ObjectResult"/> object.</returns> public static ObjectResult ToPublishResponseMessage(this List <ExerciseEntity> entities, PublishRequestMessage request, Guid eventId, HttpStatusCode httpStatusCode = HttpStatusCode.OK) { if (!entities.Any()) { var result = new ErrorObjectResult() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, Message = EventType.RecordNotFound.ToDisplayName(), StatusCode = (int)HttpStatusCode.NotFound, }; return(result); } var exercises = entities.Select(p => new Exercise() { ExerciseId = p.ExerciseId, Name = p.Exercise, Target = p.Target, Sets = p.Sets.FromJson <List <ExerciseSet> >(), AdditionalNotes = p.AdditionalNotes, } ) .ToList(); var msg = new PublishResponseMessage() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, RoutineId = request.RoutineId, Routine = request.Routine, Exercises = exercises, }; return(new ObjectResult(msg) { StatusCode = (int)httpStatusCode }); }
public void BuildsErrorWithShieldMessageWhenNoObjectOrMessageSpecifiedTest() { var statusCode = HttpStatusCode.BadRequest; var sut = new ErrorObjectResult(statusCode); sut.StatusCode.Should().Be((int)statusCode); var value = sut.Value; // The internal value is a dynamic object so we need to provide a workaround to get access to the value via Reflection // Hacky, but acceptable for testing var actual = value.GetType().GetTypeInfo().GetProperty("Message", typeof(string)).GetValue(value) as string; actual.Should().NotBeNullOrWhiteSpace(); }
public void BuildsErrorWithInternalServerErrorAndSpecifiedMessageTest() { var message = Guid.NewGuid().ToString(); var sut = new ErrorObjectResult(message); sut.StatusCode.Should().Be((int)HttpStatusCode.InternalServerError); var value = sut.Value; // The internal value is a dynamic object so we need to provide a workaround to get access to the value via Reflection // Hacky, but acceptable for testing var actual = value.GetType().GetTypeInfo().GetProperty("Message", typeof(string)).GetValue(value) as string; actual.Should().Be(message); }
/// <summary> /// Gets the <see cref="ObjectResult"/> object containing the <see cref="ExerciseResponseMessage"/> object. /// </summary> /// <param name="response"><see cref="Response"/> object.</param> /// <param name="request"><see cref="ExerciseRequestMessage"/> object.</param> /// <param name="eventId">Event ID.</param> /// <param name="exerciseId">Exercise ID.</param> /// <param name="httpStatusCode"><see cref="HttpStatusCode"/> value.</param> /// <returns>Returns the <see cref="ObjectResult"/> object.</returns> public static ObjectResult ToExerciseResponseMessage(this Response response, ExerciseRequestMessage request, Guid eventId, Guid exerciseId, HttpStatusCode httpStatusCode = HttpStatusCode.OK) { if (response.Status >= (int)HttpStatusCode.BadRequest) { var result = new ErrorObjectResult() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, Message = $"{response.Status}: {response.ReasonPhrase}", StatusCode = response.Status, }; return(result); } var msg = new ExerciseResponseMessage() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, RoutineId = request.RoutineId, Routine = request.Routine, Target = request.Target, ExerciseId = exerciseId, Exercise = request.Exercise, Sets = request.Sets, AdditionalNotes = request.AdditionalNotes, }; return(new ObjectResult(msg) { StatusCode = (int)httpStatusCode }); }
/// <summary> /// Gets the <see cref="ObjectResult"/> object containing the <see cref="RoutineResponseMessage"/> object. /// </summary> /// <param name="response"><see cref="Response"/> object.</param> /// <param name="request"><see cref="RoutineRequestMessage"/> object.</param> /// <param name="eventId">Event ID.</param> /// <param name="routineId">Routine ID.</param> /// <param name="httpStatusCode"><see cref="HttpStatusCode"/> value.</param> /// <returns>Returns the <see cref="ObjectResult"/> object.</returns> public static ObjectResult ToRoutineResponseMessage(this Response response, PublishRequestMessage request, Guid eventId, Guid routineId, HttpStatusCode httpStatusCode = HttpStatusCode.OK) { if (response.Status >= (int)HttpStatusCode.BadRequest) { var result = new ErrorObjectResult() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, Message = $"{response.Status}: {response.ReasonPhrase}", StatusCode = response.Status, }; return(result); } var msg = new RoutineResponseMessage() { Upn = request.Upn, CorrelationId = request.CorrelationId, Interface = request.Interface, SpanId = request.SpanId, EventId = eventId, RoutineId = routineId, Routine = request.Routine, }; return(new ObjectResult(msg) { StatusCode = (int)httpStatusCode }); }
/// <inheritdoc/> protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { return(await Task.Run <AuthenticateResult>(() => { if (!Request.Headers.ContainsKey("Authorization")) { _responseHeader = "Bearer realm=\"token_required\""; _responseResult = ErrorObjectResultFactory.NoAuthorizationHeader(); return AuthenticateResult.Fail(_responseResult.Error.Message); } var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); if (authHeader.Scheme != "Bearer") { _responseHeader = "Bearer error=\"invalid_request\""; _responseResult = ErrorObjectResultFactory.InvalidAuthorizationScheme(); return AuthenticateResult.Fail(_responseResult.Error.Message); } try { if (authHeader.Parameter == null) { _responseHeader = "Bearer error=\"invalid_token\""; _responseResult = ErrorObjectResultFactory.InvalidAuthorizationToken(); return AuthenticateResult.Fail(_responseResult.Error.Message); } var accessToken = _authorizeService.GetAccessToken(authHeader.Parameter); if (accessToken == null) { _responseHeader = "Bearer error=\"invalid_token\""; _responseResult = ErrorObjectResultFactory.InvalidAuthorizationToken(); return AuthenticateResult.Fail(_responseResult.Error.Message); } if (accessToken.ExpiryTime < DateUtil.Now) { _responseHeader = "Bearer error=\"invalid_token\""; _responseResult = ErrorObjectResultFactory.AuthorizationTokenExpired(); return AuthenticateResult.Fail(_responseResult.Error.Message); } var result = new List <Claim>(); foreach (var role in accessToken.Roles) { result.Add(new Claim(ClaimTypes.Role, role)); } foreach (var scope in accessToken.Scopes) { result.Add(new Claim(Scopes.ClaimType, scope)); } result.Add(new Claim(ClaimTypes.Name, accessToken.Name)); result.Add(new Claim(ClaimTypes.NameIdentifier, accessToken.PrincipalId.ToString())); var identity = new ClaimsIdentity(result.ToArray(), Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return AuthenticateResult.Success(ticket); } catch (Exception ex) { _logger.LogError(ex, ex.Message); _responseResult = ErrorObjectResultFactory.InternalServerError(); return AuthenticateResult.Fail(_responseResult.Error.Message); } })); }