HttpClientFactory increased response time with high load - asp.net-core

I am connecting to SOAP web service and I am using HttpClientFactory. Application is running on docker. Tester were testing load test with jmeter. After putting more and more load on application response time was increasing forom 100 ms to 50 sec. They have tried Soap service directly and it is performing ok.
var _client = _httpClientFactory.CreateClient("Servis");
var request = new HttpRequestMessage(
HttpMethod.Post,
"")
{
Content = new StringContent(soapRequest, Encoding.UTF8, "text/xml")
};
_client.DefaultRequestHeaders.ConnectionClose = true;
StringContent httpContent = new StringContent(soapRequest, Encoding.UTF8, "text/xml");
using var response = await _client.PostAsync(_client.BaseAddress, httpContent);
var stream = await response.Content.ReadAsStreamAsync();
var content = await _streamHelper.StreamToStringAsync(stream);
if (response.IsSuccessStatusCode)
return content;
throw new ApiException
{
StatusCode = (int)response.StatusCode,
Content = content
};
But I have tried RESTSharp and I have same problem
System.Net.ServicePointManager.DefaultConnectionLimit = 10;
var postUrl = _configuration["OibSettings:BaseAddress"];
IRestClient client = new RestClient();
client.ConfigureWebRequest((r) =>
{
r.ServicePoint.Expect100Continue = false;
r.KeepAlive = false;
});
IRestRequest request = new RestRequest
{
Resource = postUrl,
Method = Method.POST
};
request.AddHeader("Content-Type", "text/xml");
request.AddHeader("Accept", "text/xml");
request.AddParameter("text/xml", soapRequest, ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
return response.Content;
throw new ApiException
{
StatusCode = (int)response.StatusCode,
Content = response.Content
};
It starts working OK but after some time response time start to increse and. Around 5% of responses have extreme time response compared to targeted 100 ms on response.
Also some requests are timeouting and end up in error. But directly jmiter on that service it is ok.

Related

xamarin.forms ,Foursqaure api response is not displaying but works in postman and foursqaure site after providing api key ?where im wrong

private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?

Flutter: upload Image error via API function

I'm trying to upload images and some data via API from my app and I have no error in my console and I don't know what's wrong with my function.
This is the code which I use:
upload(File imageFile) async {
var user =
Provider.of<LoginUserProvider>(context, listen: false).userData.data;
DateFormat formater = DateFormat('yyyy-MM-dd');
String formatted = formater.format(dateTime);
var stream =
// ignore: deprecated_member_use
new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var headers =
Provider.of<LoginUserProvider>(context, listen: false).httpHeader;
var uri = Uri.parse(
"xyz");
var request = new http.MultipartRequest("POST", uri);
request.headers.addAll(headers);
//request.headers.addAll(Environment.requestHeaderMedia);
var multipartFile = new http.MultipartFile(
'attachment',
stream,
length,
filename: imageFile.path,
contentType: MediaType('application', 'x-tar'),
);
request.fields['section_id'] = VillaID.toString();
request.fields['date'] = formatted;
request.fields['description'] = descriptionController.text;
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
try {
final streamedResponse = await request.send();
final response = await http.Response.fromStream(streamedResponse);
print(json.decode(response.body));
final responseData = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode == 200 || response.statusCode == 201) {
return true;
}catch (error) {
print(error);
return false;
}
return true;
}
So can anyone help me with my issue, please!
you are sending the same request twice
1st
var response = await request.send();
Second
final streamedResponse = await request.send();
before sending the same request, create them again.
regarding your code you don't need to create a response again. use the first one in the other places.

TestHost generating Invalid URI: The format of the URI could not be determined

I have written some integration tests using Microsoft.AspNetCore.TestHost, But when I try to get a message as Invalid URI.
I can create TestServer successfully and able to create a client. But when I call an API using the client it says invalid URI. The URL created by TestHost is http://localhost/ and there is nothing look wrong in that URL.
I am not able to understand how could this URL be wrong. There is no other localhost website running in my machine also.
When I run my web API it's run on this URL Http:\localhost:5000 and set that as base address in my test project but it still throws the same error.
This my code to build Test Server
public MongoDbFixture()
{
var builder = new WebHostBuilder()
.UseContentRoot(GetContentRootPath())
.UseEnvironment("Test")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(GetContentRootPath())
.AddJsonFile("appsettings.Test.json")
.Build())
.UseStartup<Startup>(); // Uses Start up class from your API Host project to configure the test server
_testServer = new TestServer(builder);
Client = _testServer.CreateClient();
//Client.BaseAddress = new Uri("http://localhost:5000/");
AuthClient = _testServer.CreateClient();
//AuthenticateClient();
//AddPromptQuestions();
//SetupGoogleTranslationService();
}
This is a code to make a request.
public async Task<string> GetToken()
{
try
{
if (string.IsNullOrEmpty(token))
{
//var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("email", "kunal.ahmedabad#gmail.com"), new KeyValuePair<string, string>("password", "Password123!") });
var content = new StringContent("{email:'test#test.com',password:'Integration#85'}", Encoding.UTF8, "application/json");
var response = await Client.PostAsync(new Uri("api/Accounts/Login"), content).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
//var token = await response.Content.ReadAsAsync<OkResult>();
var newToken = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var tokenResponse = JsonConvert.DeserializeAnonymousType(newToken, new { Token = "", IsPhoneNumberConfirmed = "" });
token = tokenResponse.Token;
//token = newToken.Split(":")[1].Replace("\"", "").Replace("}", "");//todo:add better logic to read token.
return token;
}
}
catch (Exception)
{
}
return "";
}
I am not sure what is a valid URL, but this setup was working earlier.
Try changing:
new Uri("api/Accounts/Login")
To:
new Uri("api/Accounts/Login", UriKind.Relative)

POST with Restsharp doesn't work as expected

I have the following code:
var Client = new System.Net.WebClient();
var Response = Client.UploadString("myurl", PostData);
it works as expected
I am trying to do the same with Restsharp:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddBody(PostData);
var Response = client.Execute(request);
doesn't work, and:
var Client = new RestClient("myurl");
var Request = new RestRequest(Method.POST);
Request.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", PostData);
var Response = client.Execute(request);
doesn't work either...
what am I missing?

How to get Location in Response Header use HttpResponseMessage in windows phone

I want get Location in Response Header but i can't see this in Response. How to get this. Please help me.
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
FormUrlEncodedContent postData = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("background","1"),
new KeyValuePair<string,string>("line1","Content1"),
new KeyValuePair<string,string>("line2","Content2")
});
HttpResponseMessage response = await client.PostAsync("URL", postData);
string rp = await response.Content.ReadAsStringAsync();