Пример #1
0
        public override async Task WriteToStreamAsync(Type type,
                                                      object value,
                                                      Stream writeStream,
                                                      HttpContent content,
                                                      TransportContext transportContext,
                                                      CancellationToken cancellationToken)
        {
            var notSupportedMessage =
                $"The request using '{nameof(HateoasMediaTypeFormatter)}' does not have required Content-Type header '{SupportedMediaTypes.Last()}'.";

            if (!CheckSupportedContent(content))
            {
                throw new NotSupportedException(notSupportedMessage);
            }

            Resource resource = value switch
            {
                IPagination pagination => _resourceFactory.Create(pagination, type),
                IEnumerable enumerable => _resourceFactory.Create(enumerable, type),
                _ => _resourceFactory.Create(value, type)
            };
            var effectiveEncoding = SelectCharacterEncoding(content.Headers);
            var formattedResponse = _hateoasSerializer.SerializeResource(resource);
            var responseBytes     = effectiveEncoding.GetBytes(formattedResponse.ToCharArray());
            await writeStream.WriteAsync(responseBytes, 0, responseBytes.Length, cancellationToken);
        }
Пример #2
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            if (context.Object is SerializableError error)
            {
                var errorOutput = JsonSerializer.Serialize(error);
                context.HttpContext.Response.ContentType = SupportedMediaTypes.First();
                await context.HttpContext.Response.WriteAsync(errorOutput);

                return;
            }

            _resourceFactory ??= context.HttpContext.RequestServices.GetRequiredService <IResourceFactory>();
            _hateoasSerializer ??= context.HttpContext.RequestServices.GetRequiredService <IHateoasSerializer>();

            Resource resource = context.Object switch
            {
                IPagination pagination => _resourceFactory.Create(pagination, context.ObjectType),
                IEnumerable enumerable => _resourceFactory.Create(enumerable, context.ObjectType),
                _ => _resourceFactory.Create(context.Object, context.ObjectType)
            };
            var formattedResponse = _hateoasSerializer.SerializeResource(resource);

            context.HttpContext.Response.ContentType = SupportedMediaTypes.Last();
            await context.HttpContext.Response.WriteAsync(formattedResponse);
        }
    }
Пример #3
0
        public IResource AddItem(IUrl url)
        {
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var matchingItem = FindItem(url);

            if (matchingItem != null)
            {
                // Update existing item's InLink count
                matchingItem.InLinks += 1;
                return(matchingItem);
            }
            else
            {
                // Add new item
                var newItem = ResourceFactory.Create(url, CaseSensitive);

                newItem.InLinks = this.ItemCount == 0 ? 0 : 1;
                this.Items.Add(newItem);

                return(newItem);
            }
        }
 /// <summary>
 ///     Creates an instance of a <see cref="ISharedResource{TResource,TKey}" />.
 /// </summary>
 /// <param name="resourceFactory">
 ///     The resource factory to be used to create instances of the shared resource.
 ///     Is called when there is no shared resource available.
 /// </param>
 /// <typeparam name="TResource">
 ///     The type of the shared resource.
 /// </typeparam>
 /// <typeparam name="TKey">
 ///     The type of the key resource.
 /// </typeparam>
 /// <returns>
 ///     The instance of <see cref="ISharedResource{TResource,TKey}" />.
 /// </returns>
 public ISharedResource <TResource, TKey> Create <TResource, TKey>(
     IResourceFactory <TResource, TKey> resourceFactory) where TResource : IResource
 {
     return(new SharedResource <TResource, TKey>(async(key, ct) =>
     {
         var resource = resourceFactory.Create(key);
         await resource.InitializeAsync(ct);
         return resource;
     }));
 }
Пример #5
0
        public void Create_WithValidParameters_ReturnsValidFormattedResource <T>(T source) where T : class
        {
            // arrange
            var resourceLink = GetResourceLinkFromMockArrangements <T>();

            var innerLinks = new List <ResourceLink>();

            Resource resource;

            // act
            switch (source)
            {
            case IEnumerable enumerable:
                var enumerableResource = _sut.Create(enumerable, typeof(T));
                innerLinks = enumerableResource.GetItems().SelectMany(x => x.Links).ToList();
                resource   = enumerableResource;
                break;

            case IPagination pagination:
                var paginationResource = _sut.Create(pagination, typeof(T));
                innerLinks = paginationResource.GetItems().SelectMany(x => x.Links).ToList();
                resource   = paginationResource;
                break;

            default:
                resource = _sut.Create(source, typeof(T));
                break;
            }

            // assert
            Assert.NotNull(resource);
            Assert.IsAssignableFrom <Resource>(resource);
            Assert.IsType <List <ResourceLink> >(resource.Links);
            Assert.Contains(resourceLink, resource.Links);
            Assert.True(innerLinks.All(l => l == resourceLink));
        }