How to send a request to a specific URL after sending response #338

Closed
opened 2025-12-29 15:21:12 +01:00 by adam · 19 comments
Owner

Originally created by @samiransaha on GitHub (Mar 3, 2021).

The java version of wiremock supports Post-serve actions mentioned here http://wiremock.org/docs/extending-wiremock/.
By using this we can send request to a specific URL after serving mocked response to a request. Is it possible to with wiremock.net? if yes, can we configure it via JSON and does it support authentication?

Originally created by @samiransaha on GitHub (Mar 3, 2021). The java version of wiremock supports Post-serve actions mentioned here http://wiremock.org/docs/extending-wiremock/. By using this we can send request to a specific URL after serving mocked response to a request. Is it possible to with wiremock.net? if yes, can we configure it via JSON and does it support authentication?
adam added the feature label 2025-12-29 15:21:12 +01:00
adam closed this issue 2025-12-29 15:21:12 +01:00
Author
Owner

@StefH commented on GitHub (Mar 3, 2021):

You are looking for a hook / callback which will be triggered after the response has been returned?

@StefH commented on GitHub (Mar 3, 2021): You are looking for a hook / callback which will be triggered after the response has been returned?
Author
Owner

@samiransaha commented on GitHub (Mar 4, 2021):

Yes. Hook/Callback would be generic. So, that we can do something like this https://blog.jdriven.com/2020/10/using-wiremock-in-an-async-environment/

But in addition, if we can have some predefined post-serve hook like sending request to URL and surface it via JSON configuration, so that one can configure it via JSON mapping files then it would be great. Although I am not sure is it possible to inject stub code here in json config file or not because most people will need some mechanism to get actual token and send in Auth header.

Something like below:

{
    "Request": {
            "Url": "/api/v1/checkin",
            "Methods": ["post"],
            "Body": {
                  "Matcher": {
                        "Name": "JsonMatcher",
                        "Pattern": {
                    "messageId": "mockMessageId409"
                },
                        "IgnoreCase": true
                     
            }
        }
    },
    "Response": {
            "StatusCode": 409,
            "Body": "{\"errors\":[{\"code\":\"wrong_checkin\",\"message\":\"messageId : {{JsonPath.SelectToken request.body \"$.messageId\"}} conflicted\"}]}",
            "UseTransformer": true,
            "Headers": {
                  "Content-Type": "application/json"
               
        }
    },
    "PostServe": {
        "Request": {
            "Url": "http://auditmyoperation.com",
           "Method" : "Post",
           "Headers": {
             "Authorization": " skslsljd ",
             "Content-Type": "application / json"
           },
           "Body": {
             "messageId": "{{JsonPath.SelectToken request.body \"$.messageId\"}}"
           },
           "UseTransformer": true,
        }
    }
}
@samiransaha commented on GitHub (Mar 4, 2021): Yes. Hook/Callback would be generic. So, that we can do something like this https://blog.jdriven.com/2020/10/using-wiremock-in-an-async-environment/ But in addition, if we can have some predefined post-serve hook like sending request to URL and surface it via JSON configuration, so that one can configure it via JSON mapping files then it would be great. Although I am not sure is it possible to inject stub code here in json config file or not because most people will need some mechanism to get actual token and send in Auth header. Something like below: ``` json { "Request": { "Url": "/api/v1/checkin", "Methods": ["post"], "Body": { "Matcher": { "Name": "JsonMatcher", "Pattern": { "messageId": "mockMessageId409" }, "IgnoreCase": true } } }, "Response": { "StatusCode": 409, "Body": "{\"errors\":[{\"code\":\"wrong_checkin\",\"message\":\"messageId : {{JsonPath.SelectToken request.body \"$.messageId\"}} conflicted\"}]}", "UseTransformer": true, "Headers": { "Content-Type": "application/json" } }, "PostServe": { "Request": { "Url": "http://auditmyoperation.com", "Method" : "Post", "Headers": { "Authorization": " skslsljd ", "Content-Type": "application / json" }, "Body": { "messageId": "{{JsonPath.SelectToken request.body \"$.messageId\"}}" }, "UseTransformer": true, } } } ```
Author
Owner

@StefH commented on GitHub (Mar 5, 2021):

Dear @samiransaha, I did update your question with some code formatting so that it it's better readable.

I think this can be implemented, however it will take some effort.

And maybe instead of letting the user define the content, it's maybe easier to just forward the complete request and response to that callback hook. So that all data is present.

  "Hook": {
        "Request": {
            "Url": "http://auditmyoperation.com",
           "Method" : "Post",
           "Headers": {
             "Authorization": " skslsljd ",
             "Content-Type": "application / json"
           }
    }
@StefH commented on GitHub (Mar 5, 2021): Dear @samiransaha, I did update your question with some code formatting so that it it's better readable. I think this can be implemented, however it will take some effort. And maybe instead of letting the user define the content, it's maybe easier to just forward the complete request and response to that callback hook. So that all data is present. ``` json "Hook": { "Request": { "Url": "http://auditmyoperation.com", "Method" : "Post", "Headers": { "Authorization": " skslsljd ", "Content-Type": "application / json" } } ```
Author
Owner

@samiransaha commented on GitHub (Mar 6, 2021):

Thanks @StefH.
Glad to know.
I think there should be an option to send custom request body while sending request in hook along with the option to send complete request body received the way have mentioned.

@samiransaha commented on GitHub (Mar 6, 2021): Thanks @StefH. Glad to know. I think there should be an option to send custom request body while sending request in hook along with the option to send complete request body received the way have mentioned.
Author
Owner

@StefH commented on GitHub (Mar 8, 2021):

@samiransaha
I've created a preview nuget on myget:, can you please test vesion WireMock.Net.1.4.7-ci-14761 ?
-- >https://github.com/WireMock-Net/WireMock.Net/wiki/MyGet-preview-versions

Only Body or BodyAsJson is supported. No transformation (yet)

example

{
    "Guid": "755384f9-2252-433d-ae8b-445b9f1cc729",
    "Priority": 0,
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "/wh"
                }
            ]
        },
        "Methods": [
            "POST"
        ]
    },
    "Response": {
        "Body": "<xml>ok</xml>",
        "Headers": {
            "Content-Type": "application/xml"
        }
    },
    "Webhook": {
        "Request": {
            "Url": "http://any-url",
            "Method": "POST",
            "Headers": {
                "x": "x-value"
            },
            "Body": "ok?"
        }

    }
}
@StefH commented on GitHub (Mar 8, 2021): @samiransaha I've created a preview nuget on myget:, can you please test vesion WireMock.Net.1.4.7-ci-14761 ? -- >https://github.com/WireMock-Net/WireMock.Net/wiki/MyGet-preview-versions Only Body or BodyAsJson is supported. No transformation (yet) example ``` json { "Guid": "755384f9-2252-433d-ae8b-445b9f1cc729", "Priority": 0, "Request": { "Path": { "Matchers": [ { "Name": "WildcardMatcher", "Pattern": "/wh" } ] }, "Methods": [ "POST" ] }, "Response": { "Body": "<xml>ok</xml>", "Headers": { "Content-Type": "application/xml" } }, "Webhook": { "Request": { "Url": "http://any-url", "Method": "POST", "Headers": { "x": "x-value" }, "Body": "ok?" } } } ```
Author
Owner

@StefH commented on GitHub (Mar 9, 2021):

@samiransaha A new version WireMock.1.4.7-ci-14768 should now also support transformation.

Add "UseTransformer": true

@StefH commented on GitHub (Mar 9, 2021): @samiransaha A new version `WireMock.1.4.7-ci-14768` should now also support transformation. Add `"UseTransformer": true`
Author
Owner

@samiransaha commented on GitHub (Mar 10, 2021):

Thanks @StefH, I will check it.
Another thing not related to webhook, I wanted to know is it possible to configure delay before sending response via JSON or not sending any response entirely?
Something like this in java version of wiremock http://wiremock.org/docs/simulating-faults/

@samiransaha commented on GitHub (Mar 10, 2021): Thanks @StefH, I will check it. Another thing not related to webhook, I wanted to know is it possible to configure delay before sending response via JSON or not sending any response entirely? Something like this in java version of wiremock http://wiremock.org/docs/simulating-faults/
Author
Owner

@samiransaha commented on GitHub (Mar 10, 2021):

I am using the wiremock as dotnet tool. How to get your CI version for that?

@samiransaha commented on GitHub (Mar 10, 2021): I am using the wiremock as dotnet tool. How to get your CI version for that?
Author
Owner

@StefH commented on GitHub (Mar 10, 2021):

Thanks @StefH, I will check it.
Another thing not related to webhook, I wanted to know is it possible to configure delay before sending response via JSON or not sending any response entirely?
Something like this in java version of wiremock http://wiremock.org/docs/simulating-faults/

See https://github.com/WireMock-Net/WireMock.Net/wiki/Faults

@StefH commented on GitHub (Mar 10, 2021): > > > Thanks @StefH, I will check it. > Another thing not related to webhook, I wanted to know is it possible to configure delay before sending response via JSON or not sending any response entirely? > Something like this in java version of wiremock http://wiremock.org/docs/simulating-faults/ See https://github.com/WireMock-Net/WireMock.Net/wiki/Faults
Author
Owner

@StefH commented on GitHub (Mar 10, 2021):

I am using the wiremock as dotnet tool. How to get your CI version for that?

it's on the same MyGet feed:
https://www.myget.org/feed/wiremock-net/package/nuget/dotnet-WireMock

PM> Install-Package dotnet-WireMock -Version 1.4.7-ci-14780 -Source https://www.myget.org/F/wiremock-net/api/v3/index.json 
@StefH commented on GitHub (Mar 10, 2021): > > > I am using the wiremock as dotnet tool. How to get your CI version for that? it's on the same MyGet feed: https://www.myget.org/feed/wiremock-net/package/nuget/dotnet-WireMock ``` sh PM> Install-Package dotnet-WireMock -Version 1.4.7-ci-14780 -Source https://www.myget.org/F/wiremock-net/api/v3/index.json ```
Author
Owner

@samiransaha commented on GitHub (Mar 10, 2021):

Can we add Faults like no response at all? Correct me if I am wrong with the exiting Faults I will not be able to add delay before response or completely no response, to simulate server is down. Both are good candidate for fault for integration tests.
Thanks @StefH, sorry I missed that in myget link.

@samiransaha commented on GitHub (Mar 10, 2021): Can we add Faults like no response at all? Correct me if I am wrong with the exiting Faults I will not be able to add delay before response or completely no response, to simulate server is down. Both are good candidate for fault for integration tests. Thanks @StefH, sorry I missed that in myget link.
Author
Owner

@StefH commented on GitHub (Mar 12, 2021):

@samiransaha Did you have time to test it ?

@StefH commented on GitHub (Mar 12, 2021): @samiransaha Did you have time to test it ?
Author
Owner

@StefH commented on GitHub (Mar 17, 2021):

@samiransaha Did you have to test?

@StefH commented on GitHub (Mar 17, 2021): @samiransaha Did you have to test?
Author
Owner

@StefH commented on GitHub (Mar 23, 2021):

@samiransaha Can you please test this?

@StefH commented on GitHub (Mar 23, 2021): @samiransaha Can you please test this?
Author
Owner

@samiransaha commented on GitHub (Mar 23, 2021):

@StefH , Hey sorry for delay, I got sick, and was not able to catch up my emails. I will test this today, and let you know.

@samiransaha commented on GitHub (Mar 23, 2021): @StefH , Hey sorry for delay, I got sick, and was not able to catch up my emails. I will test this today, and let you know.
Author
Owner

@samiransaha commented on GitHub (Mar 23, 2021):

Hi @StefH,

I used following rule it didn't work for me looks like.
I got the response, but the webhook request generation failed.
And I see following error is console. Any Idea?

2021-03-16T00:16:20 fail: [0]
      Sending message to Webhook Mapping 'b3418573-223b-46b7-a652-e375a6767b4d' failed. Exception: System.Net.Http.HttpRequestException: Cannot assign requested address (localhost:8989)
       ---> System.Net.Sockets.SocketException (99): Cannot assign requested address
         at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
         at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token)
         at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.DefaultConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
         at System.Net.Http.ConnectHelper.ConnectAsync(Func`3 callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.ConnectHelper.ConnectAsync(Func`3 callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
         at WireMock.Owin.WireMockMiddleware.SendToWebhookAsync(IMapping mapping, RequestMessage request, ResponseMessage response) in /_/src/WireMock.Net/Owin/WireMockMiddleware.cs:line 200
{
  "Request": {
	  "Path": {
		"Matchers": [
			{
				"Name": "WildcardMatcher",
				"Pattern": "/api/user/mock_user_hook",
				"IgnoreCase": false
			}
		]
	},
	"Methods": [
	  "get"
	]
  },
  "Response": {
	"StatusCode": 200,
	"Headers": {
	  "Content-Type": "application/json",
	},
	"Body": "{
		\"Id\" : \"mock_user_cess\",
		\"Name\": \"Mock User\",
		\"City\": \"London\"
	}",
	"UseTransformer": true
  },
  "Webhook": {
        "Request": {
            "Url": "http://localhost:8989/api/saas/subscriptions/order_delete_failure_403",
            "Method": "delete",
            "Headers": {
                "mock-header": "hook-mock"
            }
        }
    }
}
@samiransaha commented on GitHub (Mar 23, 2021): Hi @StefH, I used following rule it didn't work for me looks like. I got the response, but the webhook request generation failed. And I see following error is console. Any Idea? ``` 2021-03-16T00:16:20 fail: [0] Sending message to Webhook Mapping 'b3418573-223b-46b7-a652-e375a6767b4d' failed. Exception: System.Net.Http.HttpRequestException: Cannot assign requested address (localhost:8989) ---> System.Net.Sockets.SocketException (99): Cannot assign requested address at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|283_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.DefaultConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken) at System.Net.Http.ConnectHelper.ConnectAsync(Func`3 callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken) --- End of inner exception stack trace --- at System.Net.Http.ConnectHelper.ConnectAsync(Func`3 callback, DnsEndPoint endPoint, HttpRequestMessage requestMessage, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) at System.Net.Http.DecompressionHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken) at WireMock.Owin.WireMockMiddleware.SendToWebhookAsync(IMapping mapping, RequestMessage request, ResponseMessage response) in /_/src/WireMock.Net/Owin/WireMockMiddleware.cs:line 200 ``` ``` json { "Request": { "Path": { "Matchers": [ { "Name": "WildcardMatcher", "Pattern": "/api/user/mock_user_hook", "IgnoreCase": false } ] }, "Methods": [ "get" ] }, "Response": { "StatusCode": 200, "Headers": { "Content-Type": "application/json", }, "Body": "{ \"Id\" : \"mock_user_cess\", \"Name\": \"Mock User\", \"City\": \"London\" }", "UseTransformer": true }, "Webhook": { "Request": { "Url": "http://localhost:8989/api/saas/subscriptions/order_delete_failure_403", "Method": "delete", "Headers": { "mock-header": "hook-mock" } } } } ```
Author
Owner

@StefH commented on GitHub (Mar 23, 2021):

Very strange, according to WIKI it looks fine. (https://github.com/WireMock-Net/WireMock.Net/wiki/Webhook)

See also this unit tests (819629125c/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs)

Did you try another address?

@StefH commented on GitHub (Mar 23, 2021): Very strange, according to WIKI it looks fine. (https://github.com/WireMock-Net/WireMock.Net/wiki/Webhook) See also this unit tests (https://github.com/WireMock-Net/WireMock.Net/blob/819629125ce3f34e71a31ba6a8825a13b0b8adb1/test/WireMock.Net.Tests/WireMockServer.WebhookTests.cs) Did you try another address?
Author
Owner

@samiransaha commented on GitHub (Mar 24, 2021):

Hey it worked now, there was network issue with that port for that time being.

@samiransaha commented on GitHub (Mar 24, 2021): Hey it worked now, there was network issue with that port for that time being.
Author
Owner

@StefH commented on GitHub (Mar 24, 2021):

@samiransaha Thanks for testing.
I'll merge the PR and create a new official NuGet version today or at most tomorrow.

@StefH commented on GitHub (Mar 24, 2021): @samiransaha Thanks for testing. I'll merge the PR and create a new official NuGet version today or at most tomorrow.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/WireMock.Net-wiremock#338