public async Task IHalFormatterSelected_DoesNotSerializeTest() { var halFormatter = new Mock <IHalFormatter>(); var outputFormatter = halFormatter.As <IOutputFormatter>(); var formatterSelector = FormatterSelector; formatterSelector.Setup(f => f.SelectFormatter( It.IsAny <OutputFormatterCanWriteContext>(), It.IsAny <IList <IOutputFormatter> >(), It.IsAny <MediaTypeCollection>())) .Returns(outputFormatter.Object); var inner = InnerExecutor.Object; var executor = new HalObjectResultExecutor( inner, WriterFactory.Object, formatterSelector.Object, Logger); var halFeature = new HalFeature(); var httpContext = HttpContext; httpContext.Features.Set(halFeature); var actionContext = new ActionContext { HttpContext = httpContext }; var result = ObjectResult; await executor.ExecuteAsync(actionContext, result); Assert.AreSame(actionContext, halFeature.FormattingContext.Context); Assert.AreSame(result, halFeature.FormattingContext.Result); Assert.AreSame(inner, halFeature.FormattingContext.Executor); }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Features == null) { throw new ArgumentException("Features cannot be null.", nameof(context)); } var halFeature = new HalFeature(); context.Features[typeof(HalFeature)] = halFeature; await this.next(context); if (halFeature.FormattingContext == null) { logger.LogDebug("Hal formatting context not found, other formatters are handling this response."); return; } if (context.Response.HasStarted) { logger.LogWarning("Could not transform response into a HAL response, because the response has already started."); return; } // Apparently we're dealing with a HAL response now. // Invoke the resource factory. var resourcePipelineInvoker = resourcePipeline.Create(new MvcPipeline(this.MvcPipeline)); ObjectResult result = halFeature.FormattingContext.Result; if (resourcePipelineInvoker != null) { result = await resourcePipelineInvoker.InvokeAsync(halFeature.FormattingContext); } if (context.Response.HasStarted) { logger.LogWarning("Response had already started before executing the formatter. Skipping formatter."); return; } // Now serialize the newly created resource. // By executing the modified actionresult. await halFeature.FormattingContext.Executor.ExecuteAsync( halFeature.FormattingContext.Context, result); }