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); }
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); } }