public async Task<IActionResult> Get(int? page, int? pageSize) { PaginationSet<AlbumViewModel> pagedSet = new PaginationSet<AlbumViewModel>(); try { if (await _authorizationService.AuthorizeAsync(User, "AdminOnly")) { int currentPage = page.Value; int currentPageSize = pageSize.Value; List<Album> _albums = null; int _totalAlbums = new int(); _albums = _albumRepository .AllIncluding(a => a.Photos) .OrderBy(a => a.Id) .Skip(currentPage * currentPageSize) .Take(currentPageSize) .ToList(); _totalAlbums = _albumRepository.GetAll().Count(); IEnumerable<AlbumViewModel> _albumsVM = Mapper.Map<IEnumerable<Album>, IEnumerable<AlbumViewModel>>(_albums); pagedSet = new PaginationSet<AlbumViewModel>() { Page = currentPage, TotalCount = _totalAlbums, TotalPages = (int)Math.Ceiling((decimal)_totalAlbums / currentPageSize), Items = _albumsVM }; } else { StatusCodeResult _codeResult = new StatusCodeResult(401); return new ObjectResult(_codeResult); } } catch (Exception ex) { _loggingRepository.Add(new Error() { Message = ex.Message, StackTrace = ex.StackTrace, DateCreated = DateTime.Now }); _loggingRepository.Commit(); } return new ObjectResult(pagedSet); }
public async Task GetDeltaReportHttpTriggerReturnsOk() { // Arrange var expectedResult = new StatusCodeResult((int)HttpStatusCode.OK); var function = new GetDeltaReportHttpTrigger(fakeLogger, fakeMapper, fakeDeltaReportDocumentService, fakeDeltaReportSocDocumentService); var request = BuildRequestWithValidBody("a request body"); A.CallTo(() => fakeDeltaReportDocumentService.GetByIdAsync(A <Guid> .Ignored, A <string> .Ignored)).Returns(A.Fake <DeltaReportModel>()); A.CallTo(() => fakeMapper.Map <DeltaReportApiModel>(A <DeltaReportModel> .Ignored)).Returns(A.Fake <DeltaReportApiModel>()); A.CallTo(() => fakeDeltaReportSocDocumentService.GetAsync(A <Expression <Func <DeltaReportSocModel, bool> > > .Ignored)).Returns(A.CollectionOfDummy <DeltaReportSocModel>(2)); A.CallTo(() => fakeMapper.Map <List <DeltaReportSocApiModel> >(A <List <DeltaReportSocModel> > .Ignored)).Returns(A.CollectionOfFake <DeltaReportSocApiModel>(2).ToList()); // Act var result = await function.Run(request, Guid.NewGuid()).ConfigureAwait(false); // Assert A.CallTo(() => fakeDeltaReportDocumentService.GetByIdAsync(A <Guid> .Ignored, A <string> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => fakeMapper.Map <DeltaReportApiModel>(A <DeltaReportModel> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => fakeDeltaReportSocDocumentService.GetAsync(A <Expression <Func <DeltaReportSocModel, bool> > > .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => fakeMapper.Map <List <DeltaReportSocApiModel> >(A <List <DeltaReportSocModel> > .Ignored)).MustHaveHappenedOnceExactly(); var statusResult = Assert.IsType <OkObjectResult>(result); Assert.Equal(expectedResult.StatusCode, statusResult.StatusCode); }
protected IActionResult GetHttpResponse(BaseResponse responseObject) { IActionResult actionResult; switch (responseObject.Status) { case EResponseType.Success: actionResult = Ok(responseObject); break; case EResponseType.BadRequest: actionResult = new BadRequestObjectResult(responseObject); break; case EResponseType.Exception: actionResult = new ObjectResult(responseObject); break; case EResponseType.NotFound: actionResult = new ObjectResult(responseObject); break; case EResponseType.Unauthorized: actionResult = new StatusCodeResult(401); break; case EResponseType.Forbidden: actionResult = new StatusCodeResult(403); break; default: actionResult = new ObjectResult(responseObject); break; } return(actionResult); }
public async Task <IActionResult> GetByKeyId([FromRoute] Guid keyId) { IActionResult result = null; try { BookModel bookModel = _bookServices.GetByKeyId(keyId); if (bookModel != null) { result = Ok(bookModel); } else { result = NoContent( ); } } catch (Exception ex) { _logger.LogError(ex, ex.Message); result = new StatusCodeResult(500); } return(result); }
protected override async Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = null; // Do we have any X-Version headers? if (request.Headers.Any(h => h.Key == "X-Version")) { // Grab first X-Version header var versionHeader = request.Headers.First(h => h.Key == "X-Version"); // Grab first value of that X-Version header var version = versionHeader.Value.FirstOrDefault(); // Is that value equal to our magic version value? if (version != null && version == "42") { // Execute remainder of chain, thus generating a response response = await base.SendAsync(request, cancellationToken); } } // If we get here, the version header was incorrect or missing, so create // a response saying "I'm a teapot" (we like confusing errors) if (response == null) { // Create a response by using the built-in StatusCodeResult class var result = new StatusCodeResult((HttpStatusCode)418, request); response = await result.ExecuteAsync(cancellationToken); } // Return response, which will either be result of invoking rest of chain // or our error response return(response); }
public async Task <IActionResult> Create([FromBody] User user) { IActionResult actionResult = null; try { var operation = await _userService.Create(user); if (operation.HasError) { actionResult = BuildProblemResult(operation); _logger.LogError(operation.Error.ToString()); } else { if (operation.Code == UserOperationCodes.Created) { actionResult = Created("", operation.Result); } else if (operation.Code == UserOperationCodes.Found) { actionResult = Ok(operation.Result); } else { throw new ArgumentOutOfRangeException(nameof(operation.Code), operation.Code, "User code operation not supported"); } } } catch (Exception ex) { actionResult = new StatusCodeResult(StatusCodes.Status500InternalServerError); _logger.LogError(ex, ex.Message); } return(actionResult); }
public async Task LmiWebhookHttpTriggerPostForSubscriptionValidationReturnsBadRequest() { // Arrange var expectedResult = new StatusCodeResult((int)HttpStatusCode.BadRequest); var function = new LmiWebhookHttpTrigger(fakeLogger, fakeLmiWebhookReceiverService); var request = BuildRequestWithValidBody("a request body"); var webhookRequestModel = new WebhookRequestModel { WebhookCommand = WebhookCommand.None, }; A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel); // Act var result = await function.Run(request, fakeDurableOrchestrationClient).ConfigureAwait(false); // Assert A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => fakeDurableOrchestrationClient.StartNewAsync(A <string> .Ignored, A <SocRequestModel> .Ignored)).MustNotHaveHappened(); A.CallTo(() => fakeDurableOrchestrationClient.CreateCheckStatusResponse(A <HttpRequest> .Ignored, A <string> .Ignored, A <bool> .Ignored)).MustNotHaveHappened(); var statusResult = Assert.IsType <BadRequestResult>(result); Assert.Equal(expectedResult.StatusCode, statusResult.StatusCode); }
public static IActionResult LoremIpsum(int wordCount) { double random = new Random().NextDouble(); IActionResult result; if (random < 0.6) { result = new JsonResult(new LoremIpsumResponse(Lorem.Words(wordCount))); } else if (random < 0.8) { result = new AcceptedResult(); } else if (random < 0.95) { result = new BadRequestResult(); } else { result = new StatusCodeResult(500); } return(result); }
public async Task LmiWebhookHttpTriggerPostForNoneReturnsBadRequest() { // Arrange var expectedResult = new StatusCodeResult((int)HttpStatusCode.BadRequest); var function = new LmiWebhookHttpTrigger(fakeLogger, fakeLmiWebhookReceiverService); var request = BuildRequestWithValidBody("a request body"); var webhookRequestModel = new WebhookRequestModel { WebhookCommand = WebhookCommand.None, }; A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).Returns(webhookRequestModel); // Act var result = await function.Run(request).ConfigureAwait(false); // Assert A.CallTo(() => fakeLmiWebhookReceiverService.ExtractEvent(A <string> .Ignored)).MustHaveHappenedOnceExactly(); A.CallTo(() => fakeLmiWebhookReceiverService.ReportAll()).MustNotHaveHappened(); A.CallTo(() => fakeLmiWebhookReceiverService.ReportSoc(A <Guid> .Ignored)).MustNotHaveHappened(); var statusResult = Assert.IsType <BadRequestResult>(result); Assert.Equal(expectedResult.StatusCode, statusResult.StatusCode); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, [CosmosDB( databaseName: ConstantsQ.COSMOS_DB_DATABASE_NAME, collectionName: ConstantsQ.COSMOS_DB_CONTAINER_NAME, ConnectionStringSetting = "StrCosmosCliente" )] IAsyncCollector <object> quitars, ILogger log) { IActionResult returnValue = null; try { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <QuitarProducto>(requestBody); var quitar = new QuitarProducto { QuitarProductoId = data.QuitarProductoId, Producto = data.Producto, Cantidad = data.Cantidad, Estado = data.Estado }; await quitars.AddAsync(quitar); log.LogInformation($"Cliente Insertado {quitar.Producto}"); returnValue = new OkObjectResult(quitar); } catch (Exception ex) { log.LogError($"No se inserto el cliente.Exception:{ex.Message}"); returnValue = new StatusCodeResult(StatusCodes.Status500InternalServerError); } return(returnValue); }
public async Task SpecificationRelationshipsPageModel_GivenSpecResponseReturnsBadRequest_ReturnsStatusCode400() { // Arrange string specificationId = Guid.NewGuid().ToString(); ApiResponse <SpecificationSummary> specificationResponse = new ApiResponse <SpecificationSummary>(HttpStatusCode.BadRequest); ISpecsApiClient specsApiClient = CreateSpecsApiClient(); specsApiClient .GetSpecificationSummary(Arg.Is(specificationId)) .Returns(specificationResponse); ILogger logger = CreateLogger(); SpecificationRelationshipsPageModel pageModel = CreatePageModel(specsApiClient, logger: logger); // Act IActionResult result = await pageModel.OnGetAsync(specificationId); // Assert result .Should() .BeOfType <StatusCodeResult>(); StatusCodeResult statusCodeResult = result as StatusCodeResult; statusCodeResult .StatusCode .Should() .Be(400); logger .Received(1) .Error("Failed to fetch specification with status code BadRequest"); }
public void GetUserByEmail_ReturnsInternalError_WhenExceptionOccurs() { //Arrange GetUserByEmailRequest request = new GetUserByEmailRequest(fixture.Create <string>()); mediator.When(m => m.Send(Arg.Any <GetUserByEmailRequest>())).Do( args => throw new Exception() ); //Act Task <ActionResult> task = controller.GetUserByEmail(request); task.Wait(); ActionResult result = task.Result; //Assert result.Should().NotBeNull(); result.Should().BeOfType <StatusCodeResult>(); StatusCodeResult statusCodeResult = result as StatusCodeResult; statusCodeResult.StatusCode.Should().Be(StatusCodes.Status500InternalServerError); }
/// <summary> /// Get response async <typeparamref name="T"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="codeToExecute"></param> /// <returns></returns> protected async Task <ActionResult> GetResponseAsync <T>(Func <Task <T> > codeToExecute) { ActionResult result; try { T r = await codeToExecute().ConfigureAwait(false); result = r == null ? (ActionResult)NotFound() : Ok(r); } catch (InvalidOperationException ex) { result = BadRequest(ex.Message); } catch (SecurityException) { result = Forbid(); } catch { result = new StatusCodeResult(StatusCodes.Status500InternalServerError); } return(result); }
/// <summary> /// Get response async /// </summary> /// <param name="codeToExecute"></param> /// <param name="successStatusCode"></param> /// <returns></returns> protected async Task <ActionResult> GetResponseAsync(Func <Task> codeToExecute, HttpStatusCode successStatusCode = HttpStatusCode.OK) { ActionResult result; try { await codeToExecute().ConfigureAwait(false); result = StatusCode((int)successStatusCode); } catch (InvalidOperationException ex) { result = BadRequest(ex.Message); } catch (SecurityException) { result = Forbid(); } catch { result = new StatusCodeResult(StatusCodes.Status500InternalServerError); } return(result); }
/// <summary> /// Returns redirect result. URL should be absolute. /// </summary> protected async Task <IActionResult> RedirectAsync(string url, bool permanent) { return(await Task.FromResult(permanent?StatusCodeResult.MovedPermanently(url) : StatusCodeResult.Redirect(url))); }
/// <summary> /// Returns redirect result. URL should be absolute. /// </summary> protected IActionResult Redirect(string url, bool permanent) { return(permanent ? StatusCodeResult.MovedPermanently(url) : StatusCodeResult.Redirect(url)); }
public Task ExecuteResultAsync(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } _logger = context.HttpContext.RequestServices.GetRequiredService <ILogger <PingbackResult> >(); _logger.LogInformation($"Executing PingbackResult for '{PingbackServiceResponse}'"); string content = null; int statusCode = StatusCodes.Status200OK; IActionResult actionResult = null; switch (PingbackServiceResponse) { case PingbackServiceResponse.Success: content = "<methodResponse><params><param><value><string>Thanks!</string></value></param></params></methodResponse>"; break; case PingbackServiceResponse.Error17SourceNotContainTargetUri: content = BuildErrorResponseBody(17, "The source URI does not contain a link to the target URI, and so cannot be used as a source."); break; case PingbackServiceResponse.Error32TargetUriNotExist: content = BuildErrorResponseBody(32, "The specified target URI does not exist."); break; case PingbackServiceResponse.Error48PingbackAlreadyRegistered: content = BuildErrorResponseBody(48, "The pingback has already been registered."); break; case PingbackServiceResponse.SpamDetectedFakeNotFound: actionResult = new NotFoundResult(); break; case PingbackServiceResponse.GenericError: actionResult = new StatusCodeResult(StatusCodes.Status500InternalServerError); break; case PingbackServiceResponse.InvalidPingRequest: actionResult = new BadRequestResult(); break; default: _logger.LogError($"Error Executing PingbackResult, invalid PingbackServiceResponse '{PingbackServiceResponse}'"); throw new ArgumentOutOfRangeException(); } if (null == actionResult) { actionResult = new ContentResult { Content = content, ContentType = "text/xml", StatusCode = statusCode }; } return(actionResult.ExecuteResultAsync(context)); }
public JsonResult Delete(Guid id) { StatusCodeResult responseSaving = JsonConvert.DeserializeObject <StatusCodeResult>(UiRequestManager.Instance.Post("Book", "Save", JsonConvert.SerializeObject(id))); return(Json(responseSaving.StatusCode)); }
public record OperationAsRecord(StatusCodeResult Result) : ICommand <object>
/// <summary> /// Performs the query composition after action is executed. It first tries to retrieve the IQueryable from the /// returning response message. It then validates the query from uri based on the validation settings on /// <see cref="EnableQueryAttribute"/>. It finally applies the query appropriately, and reset it back on /// the response message. /// </summary> /// <param name="actionExecutedContext">The context related to this action, including the response message, /// request message and HttpConfiguration etc.</param> public override void OnActionExecuted(ActionExecutedContext actionExecutedContext) { if (actionExecutedContext == null) { throw new ArgumentNullException(nameof(actionExecutedContext)); } HttpRequest request = actionExecutedContext.HttpContext.Request; if (request == null) { throw Error.Argument("actionExecutedContext", SRResources.ActionExecutedContextMustHaveRequest); } ActionDescriptor actionDescriptor = actionExecutedContext.ActionDescriptor; if (actionDescriptor == null) { throw Error.Argument("actionExecutedContext", SRResources.ActionContextMustHaveDescriptor); } HttpResponse response = actionExecutedContext.HttpContext.Response; // Check is the response is set and successful. if (response != null && IsSuccessStatusCode(response.StatusCode) && actionExecutedContext.Result != null) { // actionExecutedContext.Result might also indicate a status code that has not yet // been applied to the result; make sure it's also successful. StatusCodeResult statusCodeResult = actionExecutedContext.Result as StatusCodeResult; if (statusCodeResult == null || IsSuccessStatusCode(statusCodeResult.StatusCode)) { ObjectResult responseContent = actionExecutedContext.Result as ObjectResult; if (responseContent != null) { // Get collection from SingleResult. IQueryable singleResultCollection = null; SingleResult singleResult = responseContent.Value as SingleResult; if (singleResult != null) { // This could be a SingleResult, which has the property Queryable. // But it could be a SingleResult() or SingleResult<T>. Sort by number of parameters // on the property and get the one with the most parameters. PropertyInfo propInfo = responseContent.Value.GetType().GetProperties() .OrderBy(p => p.GetIndexParameters().Length) .Where(p => p.Name.Equals("Queryable", StringComparison.Ordinal)) .LastOrDefault(); singleResultCollection = propInfo.GetValue(singleResult) as IQueryable; } // Execution the action. object queryResult = OnActionExecuted( actionExecutedContext, responseContent.Value, singleResultCollection, actionDescriptor as ControllerActionDescriptor, request); if (queryResult != null) { responseContent.Value = queryResult; } } } } }
public static ActionResult <T> ToART <T>(this StatusCodeResult a) => a;
/// <summary> /// Performs the query composition after action is executed. It first tries to retrieve the IQueryable from the /// returning response message. It then validates the query from uri based on the validation settings on /// <see cref="EnableQueryAttribute"/>. It finally applies the query appropriately, and reset it back on /// the response message. /// </summary> /// <param name="actionExecutedContext">The context related to this action, including the response message, /// request message and HttpConfiguration etc.</param> public override void OnActionExecuted(ActionExecutedContext actionExecutedContext) { if (actionExecutedContext == null) { throw Error.ArgumentNull("actionExecutedContext"); } HttpRequest request = actionExecutedContext.HttpContext.Request; if (request == null) { throw Error.Argument("actionExecutedContext", SRResources.ActionExecutedContextMustHaveRequest); } ActionDescriptor actionDescriptor = actionExecutedContext.ActionDescriptor; if (actionDescriptor == null) { throw Error.Argument("actionExecutedContext", SRResources.ActionContextMustHaveDescriptor); } HttpResponse response = actionExecutedContext.HttpContext.Response; // Check is the response is set and successful. if (response != null && IsSuccessStatusCode(response.StatusCode) && actionExecutedContext.Result != null) { // actionExecutedContext.Result might also indicate a status code that has not yet // been applied to the result; make sure it's also successful. StatusCodeResult statusCodeResult = actionExecutedContext.Result as StatusCodeResult; if (statusCodeResult == null || IsSuccessStatusCode(statusCodeResult.StatusCode)) { ObjectResult responseContent = actionExecutedContext.Result as ObjectResult; if (responseContent != null) { //throw Error.Argument("actionExecutedContext", SRResources.QueryingRequiresObjectContent, // actionExecutedContext.Result.GetType().FullName); // Get collection from SingleResult. IQueryable singleResultCollection = null; SingleResult singleResult = responseContent.Value as SingleResult; if (singleResult != null) { // This could be a SingleResult, which has the property Queryable. // But it could be a SingleResult() or SingleResult<T>. Sort by number of parameters // on the property and get the one with the most parameters. PropertyInfo propInfo = responseContent.Value.GetType().GetProperties() .OrderBy(p => p.GetIndexParameters().Count()) .Where(p => p.Name.Equals("Queryable")) .LastOrDefault(); singleResultCollection = propInfo.GetValue(singleResult) as IQueryable; } // Execution the action. object queryResult = OnActionExecuted( responseContent.Value, singleResultCollection, new WebApiActionDescriptor(actionDescriptor as ControllerActionDescriptor), new WebApiRequestMessage(request), (elementClrType) => GetModel(elementClrType, request, actionDescriptor), (queryContext) => CreateAndValidateQueryOptions(request, queryContext), (statusCode) => actionExecutedContext.Result = new StatusCodeResult((int)statusCode), (statusCode, message, exception) => actionExecutedContext.Result = CreateBadRequestResult(message, exception)); if (queryResult != null) { responseContent.Value = queryResult; } } } } }
public static void AssertStatus(this StatusCodeResult result, HttpStatusCode code) { result.StatusCode.Should().Be((int)code); }
public async Task Assert_PostUserData_userdata_is_null() { StatusCodeResult result = (StatusCodeResult)await harvestsController.PostUserDataAsync(null); Assert.AreEqual(400, result.StatusCode); }
public void Assert_GetDistinctType_null_FormCollection() { StatusCodeResult result = (StatusCodeResult)harvestsController.GetDistinctType(null); Assert.AreEqual(400, result.StatusCode); }
public CustomHttpStatusCodeResult(int statusCode, StatusCodeResult statusData) : base(statusCode, statusData.Description) { _statusData = statusData; }
public UnsuccessfulQueryResult(StatusCodeResult statusCode, object data) { this.StatusCode = statusCode; this.Data = data; }
public IActionResult Redirect() { return(StatusCodeResult.Redirect("/other/go")); }
public async Task Assert_PostUserData_is_correct() { StatusCodeResult result = (StatusCodeResult)await harvestsController.PostUserDataAsync(userData); Assert.AreEqual(200, result.StatusCode); }
public TestStatusCodeResult(StatusCodeResult innerResult) : base(innerResult.StatusCode) { this.innerResult = innerResult; }
async public Task SaveDefinition_GivenValidYamlButFailedToSaveToDatabase_ReturnsStatusCode() { //Arrange string yaml = CreateRawDefinition(); byte[] byteArray = Encoding.UTF8.GetBytes(yaml); MemoryStream stream = new MemoryStream(byteArray); IHeaderDictionary headerDictionary = new HeaderDictionary(); headerDictionary .Add("yaml-file", new StringValues(yamlFile)); HttpRequest request = Substitute.For <HttpRequest>(); request .Headers .Returns(headerDictionary); request .Body .Returns(stream); ILogger logger = CreateLogger(); HttpStatusCode failedCode = HttpStatusCode.BadGateway; IDatasetRepository dataSetsRepository = CreateDataSetsRepository(); dataSetsRepository .SaveDefinition(Arg.Any <DatasetDefinition>()) .Returns(failedCode); DatasetDefinitionChanges datasetDefinitionChanges = new DatasetDefinitionChanges(); IDefinitionChangesDetectionService definitionChangesDetectionService = CreateChangesDetectionService(); definitionChangesDetectionService .DetectChanges(Arg.Any <DatasetDefinition>(), Arg.Any <DatasetDefinition>()) .Returns(datasetDefinitionChanges); DefinitionsService service = CreateDefinitionsService(logger, dataSetsRepository, definitionChangesDetectionService: definitionChangesDetectionService); //Act IActionResult result = await service.SaveDefinition(request); //Assert result .Should() .BeOfType <StatusCodeResult>(); StatusCodeResult statusCodeResult = (StatusCodeResult)result; statusCodeResult .StatusCode .Should() .Be(502); logger .Received(1) .Error(Arg.Is($"Failed to save yaml file: {yamlFile} to cosmos db with status 502")); }