I set up a fake json server (fake-api-jwt-json-server) taken from GitHub on my PC. Using url http://localhost:8000/auth/login, I am able to post to it successfully from Postman but when I tried from Visual Studio 2019, I got the error 'No connection could be made because the target machine actively refused it' (see error detail below). The same was the result when I tried another fake json server. In both cases, the url included 'http://localhost'. From VS, I am able to get responses from api endpoints that do not include 'http://localhost' with no problem. Why are the localhost api urls not working when I try them from VS? I have tried switching off my firewall.
The error message:-
jServerAGetAccessToken Source: Tests.cs line 27 Duration: 2.1 sec
Message:
System.AggregateException : One or more errors occurred. (No connection could be made because the target machine actively refused it.)
----> System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it.
----> System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it.
Stack Trace:
Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
Task1.GetResultCore(Boolean waitCompletionNotification) Task
1.get_Result()
Tests.jServerAGetAccessToken() line 50
--HttpRequestException
ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) HttpMethods.PostWithKey(Dictionary
2 url, StringContent postParamaters) line 92
--SocketException
ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
And now my code:-
public async Task<string> PostWithKey(Dictionary<string, string> url, StringContent postParamaters)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url["endpoint"]);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
using (HttpResponseMessage response = await client.PostAsync(url["resource"] + url["paramaters"], postParamaters))
{
var strJson = response.Content.ReadAsStringAsync().Result;
status = response.StatusCode.ToString();
statusCode = (int)response.StatusCode;
return strJson;
}
}
}
Also,
[Test]
public void jServerAGetAccessToken()
{
string jsonPath = NunitTestContext.CurrentContext.TestDirectory + @"..\..\..\..\Files\";
var jsonFile = "LoginCredentials.json";
Dictionary<string, string> postUrl = new Dictionary<string, string>()
{
{ "endpoint", "http://127.0.0.1"},
{ "resource", ":8000/auth/login"},
{ "paramaters", ""},
{ "key", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlY2hpZUBlbWFpbC5jb20iLCJwYXNzd29yZCI6InRlY2hpZSIsImlhdCI6MTYxMDYzNjYzNywiZXhwIjoxNjEwNjQwMjM3fQ.CW6adTp9PNT3oTiQVKSy3HHYZMimUM12V5aWUiyDPoc"}
};
Credentials jsonDeserialised = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText(jsonPath + jsonFile));
_credentials.email = jsonDeserialised.email;
_credentials.password = jsonDeserialised.password;
StringContent jsonData = new StringContent(JsonConvert.SerializeObject(_credentials), Encoding.UTF8, "application/json");
var result = PostWithKey(postUrl, jsonData).Result;
var response = JsonConvert.DeserializeObject<Credentials>(result);
Assert.AreEqual("Created", status, "Status text is incorrect");
Assert.AreEqual(201, statusCode, "Status text is incorrect");
}