Question: Unable get response from wiremock.net server in c# #147

Closed
opened 2025-12-29 08:22:50 +01:00 by adam · 16 comments
Owner

Originally created by @Elangopalakrishnan on GitHub (Oct 16, 2018).

Hi ,

Problem:

I'm trying to implement the wiremock in c#, For that I have downloaded the wiremock .net library from NuGet,

And I'm trying to do GET method , but i'm getting below error message :(

From C#

"Id = 17, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}""
if i use "await" - It is waiting for long time then it is returning 404 file not found error,

From Post Man

Could not get any response
There was an error connecting to http://localhost:62092/product/p0001.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

Versions of packages:
WireMock.Net - 1.0.3.16
System.Net.Http - 4.3.3

Code snippet:

_server = FluentMockServer.Start();
            _server
                      .Given(Request.Create().WithUrl("/product/p0001").UsingGet())
                      .RespondWith(
                        Response.Create()
                          .WithStatusCode(200)                         
                          .WithBody(@"{ msg: ""Hello world!""}"));
            var getResp = new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/product/p0001");

Please advice me what I'm missing here :(

Thanks in advance!
Elango

Originally created by @Elangopalakrishnan on GitHub (Oct 16, 2018). Hi , ## Problem: I'm trying to implement the wiremock in c#, For that I have downloaded the wiremock .net library from NuGet, And I'm trying to do GET method , but i'm getting below error message :( ### From C# "Id = 17, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"" if i use "await" - It is waiting for long time then it is returning 404 file not found error, ### From Post Man ``` Could not get any response There was an error connecting to http://localhost:62092/product/p0001. Why this might have happened: The server couldn't send a response: Ensure that the backend is working properly Self-signed SSL certificates are being blocked: Fix this by turning off 'SSL certificate verification' in Settings > General Proxy configured incorrectly Ensure that proxy is configured correctly in Settings > Proxy Request timeout: Change request timeout in Settings > General ``` **Versions of packages:** WireMock.Net - 1.0.3.16 System.Net.Http - 4.3.3 ### Code snippet: ``` c# _server = FluentMockServer.Start(); _server .Given(Request.Create().WithUrl("/product/p0001").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithBody(@"{ msg: ""Hello world!""}")); var getResp = new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/product/p0001"); ``` Please advice me what I'm missing here :( Thanks in advance! Elango
adam closed this issue 2025-12-29 08:22:51 +01:00
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

Which Framework do you use ?
.NET 4.x.x ?
Or
.NET Core 2.x

@StefH commented on GitHub (Oct 16, 2018): Which Framework do you use ? .NET 4.x.x ? Or .NET Core 2.x
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Target framewok:
.NET Core 2.0

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Target framewok: .NET Core 2.0
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

  1. Use WithPath instead WithUrl
  2. HttpClient uses an async method

Solution:

class Program
{
    static void Main(string[] args)
    {
        RunAsync().GetAwaiter().GetResult();
    }

    static async Task RunAsync()
    {
        var server = FluentMockServer.Start();
        server
            .Given(Request.Create().WithPath("/product/p0001").UsingGet())
            .RespondWith(
                Response.Create()
                    .WithStatusCode(200)
                    .WithBody(@"{ msg: ""Hello world!""}"));
        var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001");

        Console.WriteLine(getResp);
    }
}
@StefH commented on GitHub (Oct 16, 2018): 1. Use `WithPath` instead `WithUrl` 2. HttpClient uses an async method Solution: ``` c# class Program { static void Main(string[] args) { RunAsync().GetAwaiter().GetResult(); } static async Task RunAsync() { var server = FluentMockServer.Start(); server .Given(Request.Create().WithPath("/product/p0001").UsingGet()) .RespondWith( Response.Create() .WithStatusCode(200) .WithBody(@"{ msg: ""Hello world!""}")); var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001"); Console.WriteLine(getResp); } } ```
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

hi @StefH ,

Thanks for reply, Its working fine,

For POST method , How can i check POST's response in our c# code,
like GET has - var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001");

Can you please share the some example .json files for POST method,
It would be grateful.

Thanks!
Elango

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): hi @StefH , Thanks for reply, Its working fine, For POST method , How can i check POST's response in our c# code, like GET has - var getResp = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/product/p0001"); Can you please share the some example .json files for POST method, It would be grateful. Thanks! Elango
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Hi @StefH

I used below code, to get post's response ,

 StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json");
 HttpResponseMessage response = await client.PostAsync("api/products/save", content);
 string content = await response.Content.ReadAsStringAsync();

Thanks!
Elango

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Hi @StefH I used below code, to get post's response , ``` c# StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("api/products/save", content); string content = await response.Content.ReadAsStringAsync(); ``` Thanks! Elango
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Sorry. I couldn't get you ...

Thanks & Regards
Elangopalakrishnan.V

On Oct 16, 2018 21:15, "Stef Heyenrath" notifications@github.com wrote:

That would be:

string content = await response.Content.ReadAsStringAsync();


You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/WireMock-Net/WireMock.Net/issues/213#issuecomment-430289319,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AZpriQ4UnLjYQ9LZTOKyWm_4iQHv3367ks5ulf8SgaJpZM4XePnA
.

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Sorry. I couldn't get you ... Thanks & Regards Elangopalakrishnan.V On Oct 16, 2018 21:15, "Stef Heyenrath" <notifications@github.com> wrote: > That would be: > > string content = await response.Content.ReadAsStringAsync(); > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/WireMock-Net/WireMock.Net/issues/213#issuecomment-430289319>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AZpriQ4UnLjYQ9LZTOKyWm_4iQHv3367ks5ulf8SgaJpZM4XePnA> > . >
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

BTW you can use on github issues:

triple single quotes space C# ( ``` c#) to start a code block
and
tripple single quotes space (```) to end a code block

@StefH commented on GitHub (Oct 16, 2018): BTW you can use on github issues: triple single quotes space C# (` ``` c#`) to start a code block and tripple single quotes space (` ``` `) to end a code block
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

AH, you need a JSON mapping example.

Something like this?

{
    "Request": {
        "Path": {
            "Matchers": [
                {
                    "Name": "WildcardMatcher",
                    "Pattern": "api/products/save"
                }
            ]
        },
        "Methods": [
            "post"
        ]
    },
    "Response": {
        "BodyAsJson": { "body": "static mapping" },
        "Headers": {
            "Content-Type": "application/json"
        }
    }
}
@StefH commented on GitHub (Oct 16, 2018): AH, you need a JSON mapping example. Something like this? ``` js { "Request": { "Path": { "Matchers": [ { "Name": "WildcardMatcher", "Pattern": "api/products/save" } ] }, "Methods": [ "post" ] }, "Response": { "BodyAsJson": { "body": "static mapping" }, "Headers": { "Content-Type": "application/json" } } } ```
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

See also WIKI
https://github.com/WireMock-Net/WireMock.Net/wiki/Request-Matching

@StefH commented on GitHub (Oct 16, 2018): See also WIKI https://github.com/WireMock-Net/WireMock.Net/wiki/Request-Matching
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

BTW you can also use the gitter channel for asking questions.
https://gitter.im/wiremock_dotnet/Lobby

@StefH commented on GitHub (Oct 16, 2018): BTW you can also use the gitter channel for asking questions. https://gitter.im/wiremock_dotnet/Lobby
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

@StefH ,

I have two .json files one is for request and one is for response,
lets say req.json and resp.json,
I'm just reading those jsons and storing in two string variables,
Then I'm just deserializing and creating objects,
and my code is,

String requestpath = @"C:\Users\req.json";
String req = n.GetJSONObjectFromFile(requestpath);
String responsePath = @"C:\Users\resp.json";
String resp = n.GetJSONObjectFromFile(responsePath);
Requests ob = JsonConvert.DeserializeObject<Requests>(req);
Resp obresp = JsonConvert.DeserializeObject<Resp>(resp);
StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json");
	server
	  .Given(
		Request.Create()
			.WithPath("/emailValidate")
			.WithBody(new JsonMatcher(JsonConvert.SerializeObject(ob))).UsingPost())
			.RespondWith(
		Response.Create()
			.WithStatusCode(200)
			.WithHeader("Constent-Type", "application/json")                   
			.WithBody(resp));   
HttpResponseMessage response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/emailValidate", content);
Console.WriteLine(JsonConvert.SerializeObject(obresp));

req.json

{  
   "Email":"myemail@gmail.com"
}

resp.json

{  
   "isValid":true,
   "certainty":"Verified"   
}

But i don't know , how i need to match and all, i saw above site, but i don't understand why we are using matchers.

Thanks
Elango

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): @StefH , I have two .json files one is for request and one is for response, lets say req.json and resp.json, I'm just reading those jsons and storing in two string variables, Then I'm just deserializing and creating objects, and my code is, ``` c# String requestpath = @"C:\Users\req.json"; String req = n.GetJSONObjectFromFile(requestpath); String responsePath = @"C:\Users\resp.json"; String resp = n.GetJSONObjectFromFile(responsePath); Requests ob = JsonConvert.DeserializeObject<Requests>(req); Resp obresp = JsonConvert.DeserializeObject<Resp>(resp); StringContent content = new StringContent(JsonConvert.SerializeObject(ob), Encoding.UTF8, "application/json"); server .Given( Request.Create() .WithPath("/emailValidate") .WithBody(new JsonMatcher(JsonConvert.SerializeObject(ob))).UsingPost()) .RespondWith( Response.Create() .WithStatusCode(200) .WithHeader("Constent-Type", "application/json") .WithBody(resp)); HttpResponseMessage response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/emailValidate", content); Console.WriteLine(JsonConvert.SerializeObject(obresp)); ``` req.json ``` js { "Email":"myemail@gmail.com" } ``` resp.json ``` js { "isValid":true, "certainty":"Verified" } ``` But i don't know , how i need to match and all, i saw above site, but i don't understand why we are using matchers. Thanks Elango
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

You need to use use a matcher for the body to make sure that only a request with a specific body is matched.

So on your case you can use code like:

var server = FluentMockServer.Start();
server
    .Given(Request
    .Create()
    .WithPath("/jsonmatcher1")
    .WithBody(new JsonMatcher("{ \"Email\": \"myemail@gmail.com\" }"))
    .UsingPost())
    .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
    .RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));
@StefH commented on GitHub (Oct 16, 2018): You need to use use a matcher for the body to make sure that only a request with a specific body is matched. So on your case you can use code like: ``` c# var server = FluentMockServer.Start(); server .Given(Request .Create() .WithPath("/jsonmatcher1") .WithBody(new JsonMatcher("{ \"Email\": \"myemail@gmail.com\" }")) .UsingPost()) .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2") .RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }")); ```
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Hi , I'm using same code, and getting response like below, But i'm getting error 500.
How we can get responses ???

server
.Given(Request
.Create()
.WithPath("/jsonmatcher1")
.WithBody(new JsonMatcher("{ "Email": "myemail@gmail.com" }"))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
.RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));
StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "myemail@gmail.com" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

Thanks!
Elango

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Hi , I'm using same code, and getting response like below, But i'm getting error 500. How we can get responses ??? server .Given(Request .Create() .WithPath("/jsonmatcher1") .WithBody(new JsonMatcher("{ \"Email\": \"myemail@gmail.com\" }")) .UsingPost()) .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2") .RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }")); StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ \"Email\": \"myemail@gmail.com\" }"), Encoding.UTF8, "application/json"); HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent); Thanks! Elango
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Hi , I'm using same code, and getting response like below, But i'm getting error 500.
How we can get responses ???

server
.Given(Request
.Create()
.WithPath("/jsonmatcher1")
.WithBody(new JsonMatcher("{ "Email": "myemail@gmail.com" }"))
.UsingPost())
.WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2")
.RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }"));
StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "myemail@gmail.com" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

Thanks!
Elango

Sorry , by mistake closed :(

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Hi , I'm using same code, and getting response like below, But i'm getting error 500. How we can get responses ??? server .Given(Request .Create() .WithPath("/jsonmatcher1") .WithBody(new JsonMatcher("{ "Email": "myemail@gmail.com" }")) .UsingPost()) .WithGuid("debaf408-3b23-4c04-9d18-ef1c020e79f2") .RespondWith(Response.Create().WithBody(@"{ ""isValid"": ""true"" }")); StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "myemail@gmail.com" }"), Encoding.UTF8, "application/json"); HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent); Thanks! Elango Sorry , by mistake closed :(
Author
Owner

@Elangopalakrishnan commented on GitHub (Oct 16, 2018):

Can you please review

StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "myemail@gmail.com" }"), Encoding.UTF8, "application/json");
HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent);

These codes are correct??

Thanks
Elango

@Elangopalakrishnan commented on GitHub (Oct 16, 2018): Can you please review StringContent cnent = new StringContent(JsonConvert.SerializeObject("{ "Email": "myemail@gmail.com" }"), Encoding.UTF8, "application/json"); HttpResponseMessage rponse = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", cnent); These codes are correct?? Thanks Elango
Author
Owner

@StefH commented on GitHub (Oct 16, 2018):

use

var stringContent1 = new StringContent("{ \"Email\": \"myemail@gmail.com\" }", Encoding.UTF8, "application/json");
var postResponse1 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent1);
string postContent1 = await postResponse1.Content.ReadAsStringAsync();
Console.WriteLine(postContent1);

// or

var stringContent2 = new StringContent(JsonConvert.SerializeObject(new { Email = "myemail@gmail.com" }), Encoding.UTF8, "application/json");
var postResponse2 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent2);
string postContent2 = await postResponse2.Content.ReadAsStringAsync();
Console.WriteLine(postContent2);
@StefH commented on GitHub (Oct 16, 2018): use ``` c# var stringContent1 = new StringContent("{ \"Email\": \"myemail@gmail.com\" }", Encoding.UTF8, "application/json"); var postResponse1 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent1); string postContent1 = await postResponse1.Content.ReadAsStringAsync(); Console.WriteLine(postContent1); // or var stringContent2 = new StringContent(JsonConvert.SerializeObject(new { Email = "myemail@gmail.com" }), Encoding.UTF8, "application/json"); var postResponse2 = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/jsonmatcher1", stringContent2); string postContent2 = await postResponse2.Content.ReadAsStringAsync(); Console.WriteLine(postContent2); ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/WireMock.Net#147