diff --git a/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs b/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs index 1f27fa23..a3240938 100644 --- a/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs +++ b/src/WireMock.Net/ResponseBuilders/IBodyResponseBuilder.cs @@ -18,6 +18,17 @@ namespace WireMock.ResponseBuilders /// A . IResponseBuilder WithBody([NotNull] string body, [CanBeNull] string destination = BodyDestinationFormat.SameAsSource, [CanBeNull] Encoding encoding = null); + + /// + /// WithBody : Create a ... response based on a callback function. + /// + /// The delegate to build the body. + /// The Body Destination format (SameAsSource, String or Bytes). + /// The body encoding. + /// A . + IResponseBuilder WithBody([NotNull] Func bodyFactory, [CanBeNull] string destination = BodyDestinationFormat.SameAsSource, [CanBeNull] Encoding encoding = null); + + /// /// WithBody : Create a ... response based on a bytearray. /// diff --git a/src/WireMock.Net/ResponseBuilders/Response.cs b/src/WireMock.Net/ResponseBuilders/Response.cs index 58cfe124..292e0b0d 100644 --- a/src/WireMock.Net/ResponseBuilders/Response.cs +++ b/src/WireMock.Net/ResponseBuilders/Response.cs @@ -167,6 +167,13 @@ namespace WireMock.ResponseBuilders return this; } + /// + public IResponseBuilder WithBody(Func bodyFactory, string destination = BodyDestinationFormat.SameAsSource, + Encoding encoding = null) + { + return WithCallback(req => new ResponseMessage {Body = bodyFactory(req)}); + } + /// public IResponseBuilder WithBody(byte[] body, string destination, Encoding encoding = null) { diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.cs b/test/WireMock.Net.Tests/FluentMockServerTests.cs index 3052c02b..0c175999 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.cs +++ b/test/WireMock.Net.Tests/FluentMockServerTests.cs @@ -232,6 +232,27 @@ namespace WireMock.Net.Tests Check.That(response).IsEqualTo("Hello world!"); } + [Fact] + public async Task FluentMockServer_Should_respond_to_request_bodyAsCallback() + { + // given + _server = FluentMockServer.Start(); + + _server + .Given(Request.Create() + .WithPath("/foo") + .UsingGet()) + .RespondWith(Response.Create() + .WithStatusCode(200) + .WithBody(req => $"{{ path: '{req.Path}' }}")); + + // when + var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"); + + // then + Check.That(response).IsEqualTo("{ path: '/foo' }"); + } + [Fact] public async Task FluentMockServer_Should_respond_to_request_bodyAsBase64() {