Comments (13)
This is fixed in 1.5.1 (just released)
from mockhttp.
Can you provide a reproducible example? The following succeeds for me:
var mockHttp = new MockHttpMessageHandler();
var mockedRequest = mockHttp.When("/path");
mockedRequest.Respond(req => new StringContent("test", Encoding.UTF8, "text/plain"));
var request = new HttpRequestMessage(HttpMethod.Post, "http://www.tempuri.org/path?apple=red&pear=green")
{
Content = new StringContent("testing")
};
string contentA;
using (var responseA = mockedRequest.SendAsync(request, CancellationToken.None).Result)
{
contentA = responseA.Content.ReadAsStringAsync().Result;
}
string contentB;
using (var responseB = mockedRequest.SendAsync(request, CancellationToken.None).Result)
{
contentB = responseB.Content.ReadAsStringAsync().Result;
}
from mockhttp.
Hi there, I haven't heard back from you on this issue for a while so I'm going to close it. Please feel free to create a new issue if you manage to create a reproducible example.
from mockhttp.
from mockhttp.
I'm going to close this issue due to lack of activity. If you're able to create a "MCV" example, I'm more than happy to dive deeper and fix the underlying issue.
from mockhttp.
Hello, I have a reproducible example below
using System.Net.Http;
using RichardSzalay.MockHttp;
namespace MockHttpClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var mockHandler = new MockHttpMessageHandler();
mockHandler.When("*").Respond("text/html", "");
var regularHandler = new HttpClientHandler();
var repository = new Repository(mockHandler);
// Use below handler works fine.
// var repository = new Repository(regularHandler);
Console.WriteLine(repository.Get1());
Console.WriteLine(repository.Get2());
}
}
class Repository
{
private readonly HttpMessageHandler handler;
public Repository(HttpMessageHandler handler)
{
this.handler = handler;
}
public string Get1()
{
HttpClient client = new HttpClient(handler, false);
return client.GetStringAsync("https://www.google.com").Result;
}
public string Get2()
{
HttpClient client = new HttpClient(handler, false);
return client.GetStringAsync("https://github.com").Result;
}
}
}
Below is the output.
/tmp/MockHttpClient ยป dotnet run . chengbo@Bo-MBP
Hello World!
Unhandled Exception: System.AggregateException: One or more errors occurred. (Cannot access a disposed object.
Object name: 'System.Net.Http.HttpResponseMessage'.) ---> System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.HttpResponseMessage'.
at System.Net.Http.HttpResponseMessage.CheckDisposed()
at System.Net.Http.HttpResponseMessage.set_RequestMessage(HttpRequestMessage value)
at RichardSzalay.MockHttp.MockHttpMessageHandler.<>c__DisplayClass13_0.<SendAsync>b__1(Task`1 resp)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.HttpClient.<FinishSendAsyncUnbuffered>d__59.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.HttpClient.<GetStringAsyncCore>d__27.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at MockHttpClient.Repository.Get2() in /private/tmp/MockHttpClient/Program.cs:line 42
at MockHttpClient.Program.Main(String[] args) in /private/tmp/MockHttpClient/Program.cs:line 20
MacOS 10.12.6
Dotnet Core 2.0
from mockhttp.
Oddly I still can't reproduce the problem. I'm on Windows, but it works against both .NET and .NET Core.
Am I correct in assuming you're using MockHttp 1.5.0? It sounds like something that would have been a problem before 1.3.1
from mockhttp.
Thanks for pointing out this, I've just checked my .csproj file, there was
<PackageReference Include="RichardSzalay.MockHttp" Version="3.0.0" />
in there.
Then I used below command to force install 1.5.0, everything works fine.
dotnet add package RichardSzalay.MockHttp --version 1.5.0
I don't know why 3.0.0 is installed without version parameter.
from mockhttp.
That's very strange. 3.0.0 was published in error in place of 1.3.0 but was unlisted so it shouldn't have been accepted unless explicitly requested.
from mockhttp.
Yes, and it would be great if you could add a note for this in README file to prevent others from installing a wrong version without specifying version parameter.
from mockhttp.
Done, and I've also logged a bug with the dotnet cli team: https://github.com/dotnet/cli/issues/7492
from mockhttp.
Hi Richard,
I confirm I have version 1.5.0, my code is a bit different, since I do an explicit dispose on the HttpResponseMessage after extracting the content:
public async Task HttpSendAsync(HttpRequestMessage requestMessage, X509Certificate2 sslCertificate = null)
{
var httpClient = GetHttpClient(sslCertificate);
return await CallWithCircuitBreakerAsync(requestMessage.RequestUri.AbsoluteUri, async () =>
{
HttpResponseMessage httpResponse = null;
try
{
httpResponse = await httpClient.SendAsync(requestMessage);
var responseContent = await GetContentAsync(httpResponse);
return responseContent;
}
catch (Exception e)
{
logger.Warn($"httpClient.HttpSendAsync failed. Method: {requestMessage.Method} Url: {requestMessage.RequestUri.AbsoluteUri} Error: {e.Message}",e);
throw;
}
finally
{
// Dispose response object to avoid memory leak
httpResponse?.Dispose();
}
});
}
from mockhttp.
I can now reproduce the issue, and I'll look at patching it. FYI there's no need to dispose the response unless you are keeping a reference to it somewhere.
var handler = new MockHttpMessageHandler();
handler.When("*").Respond(HttpStatusCode.OK);
var client = handler.ToHttpClient();
var responseA = client.GetAsync("https://localhost/").GetAwaiter().GetResult();
responseA.Dispose();
var responseB = client.GetAsync("https://localhost/").GetAwaiter().GetResult();
from mockhttp.
Related Issues (20)
- Documentation Request HOT 3
- Adding Response Headers
- Question: Matching Query with XML HOT 4
- Feature Request: Support BaseAddress and DefaultRequestHeaders HOT 3
- Not Compatible with Sync HttpClient Send HOT 4
- Matcher async support HOT 4
- PostAsync with When() returns NotFound - but only when an Expect() is also defined HOT 6
- How to add additional conditions to .When()? HOT 1
- HttpClientJsonExtensions.PostAsJsonAsync Throws NullReferenceException When Serializing the Property/Value Message = "Message:" HOT 2
- Package does not support URI containing fragments HOT 3
- Not seeing anyway to follow redirects HOT 2
- Does not support URL-encoded content in URIs HOT 2
- Lib cannot be used in .NET7 projects HOT 3
- NullReferenceException if response is not configured. HOT 3
- requestExpectations queue not thread safe HOT 2
- Allow mocking IHttpClientFactory HOT 3
- Overwrite same endpoint with different result HOT 3
- Feature request: clear match counts HOT 4
- Can't Match Using WithFormData, WithHeaders HOT 5
- Library status HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mockhttp.