Combine a value from query with string data in WithBodyAsJson #482

Closed
opened 2025-12-29 15:24:48 +01:00 by adam · 3 comments
Owner

Originally created by @mattisking on GitHub (Jan 19, 2023).

Originally assigned to: @StefH on GitHub.

I'm trying something which I'm sure is simple but I can't seem to get working. Basically I want to take a value from the query and echo it back inside a json object, but with some additional hardcoded information included. Here's the example I'm working with:
(yes, I'm mocking an OAuth call)

         _server
            .Given(Request.Create()
                .WithPath(new WildcardMatcher("/oauth2/v1/token", true))
                .UsingPost()
                ).AtPriority(1)
                .RespondWith(Response.Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/json")
                .WithBodyAsJson(
                    new 
                    { 
                        access_token = "{{Random Type='Text' Min=28 Max=28 UseNumber=true UseSpecial=false UseLetter=true UseSpace=false UseNullValues=false UseUppercase=true UseLowercase=true}}",
                        scope = "{{request.query.scope}}" + " helloworld",
                        token_type = "Bearer",
                        expires_in = 86400
                    }).WithTransformer()
                );

An example URL:
https://localhost:7012/oauth2/v1/token?grant_type=client_credentials&scope=scope1 scope2 scope3

I'd like to get back something like:

{
    "access_token": "GrNAkBKeplrxBRRtGEfIzpoaIAWN",
    "scope": "scope1 scope2 scope3 helloworld",
    "token_type": "Bearer",
    "expires_in": 86400
}

My " helloworld" is ignored, I suspect it's dropped in the transformer.

Originally created by @mattisking on GitHub (Jan 19, 2023). Originally assigned to: @StefH on GitHub. I'm trying something which I'm sure is simple but I can't seem to get working. Basically I want to take a value from the query and echo it back inside a json object, but with some additional hardcoded information included. Here's the example I'm working with: (yes, I'm mocking an OAuth call) ``` c# _server .Given(Request.Create() .WithPath(new WildcardMatcher("/oauth2/v1/token", true)) .UsingPost() ).AtPriority(1) .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBodyAsJson( new { access_token = "{{Random Type='Text' Min=28 Max=28 UseNumber=true UseSpecial=false UseLetter=true UseSpace=false UseNullValues=false UseUppercase=true UseLowercase=true}}", scope = "{{request.query.scope}}" + " helloworld", token_type = "Bearer", expires_in = 86400 }).WithTransformer() ); ``` An example URL: https://localhost:7012/oauth2/v1/token?grant_type=client_credentials&scope=scope1 scope2 scope3 I'd like to get back something like: ``` json { "access_token": "GrNAkBKeplrxBRRtGEfIzpoaIAWN", "scope": "scope1 scope2 scope3 helloworld", "token_type": "Bearer", "expires_in": 86400 } ``` My " helloworld" is ignored, I suspect it's dropped in the transformer.
adam added the question label 2025-12-29 15:24:48 +01:00
adam closed this issue 2025-12-29 15:24:49 +01:00
Author
Owner

@StefH commented on GitHub (Jan 19, 2023):

@mattisking
The solution is to use String.Append and String.Join.

Example:

[Fact]
    public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_Handlebars_StringAppend()
    {
        // Assign
        var request = new RequestMessage(new UrlDetails("https://localhost/token?scope=scope1 scope2 scope3"), "POST", ClientIp);

        var responseBuilder = Response.Create()
            .WithBodyAsJson(
                new
                {
                    scope = "{{String.Append (String.Join request.query.scope) \" helloworld\" }}"
                })
            .WithTransformer();

        // Act
        var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false);

        // Assert
        JsonConvert.SerializeObject(response.Message.BodyData!.BodyAsJson).Should().Be("{\"scope\":\"scope1 scope2 scope3 helloworld\"}");
    }
@StefH commented on GitHub (Jan 19, 2023): @mattisking The solution is to use `String.Append` and `String.Join`. Example: ``` c# [Fact] public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_Handlebars_StringAppend() { // Assign var request = new RequestMessage(new UrlDetails("https://localhost/token?scope=scope1 scope2 scope3"), "POST", ClientIp); var responseBuilder = Response.Create() .WithBodyAsJson( new { scope = "{{String.Append (String.Join request.query.scope) \" helloworld\" }}" }) .WithTransformer(); // Act var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false); // Assert JsonConvert.SerializeObject(response.Message.BodyData!.BodyAsJson).Should().Be("{\"scope\":\"scope1 scope2 scope3 helloworld\"}"); } ```
Author
Owner

@mattisking commented on GitHub (Jan 20, 2023):

Thanks! Is there a section of the help that digs into the available options:
"{{String.Append (String.Join request.query.scope) " helloworld" }}"

String.Append
String.Join

@mattisking commented on GitHub (Jan 20, 2023): Thanks! Is there a section of the help that digs into the available options: "{{String.Append (String.Join request.query.scope) \" helloworld\" }}" String.Append String.Join
Author
Owner

@StefH commented on GitHub (Jan 20, 2023):

These methods are extensions to Handlebars.Net:

See https://github.com/Handlebars-Net/Handlebars.Net.Helpers/wiki/String

@StefH commented on GitHub (Jan 20, 2023): These methods are extensions to Handlebars.Net: See https://github.com/Handlebars-Net/Handlebars.Net.Helpers/wiki/String
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/WireMock.Net-wiremock#482