PostAsync is not working when URL contain port - c#

My .net application try to access external API by using the code below...
using (var keyClient = new HttpClient())
{
keyClient.BaseAddress = new Uri(ConfigurationManager.AppSettings["webshopurl"]);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("api_username",
ConfigurationManager.AppSettings["webshopAPIUserName"]),
new KeyValuePair<string, string>("api_password",
ConfigurationManager.AppSettings["webshopAPIPassword"])
});
var result = keyClient.PostAsync("/api/v1/key.php", content).Result;
token = result.Content.ReadAsStringAsync().Result;
}
When calling from local machine it works properly. But when it is hosted in online server URL such like http://app.test.net:5000/test it is not calling to the API. If we host such a URL like http://app.test.net/test it is working properly.
What is the reason for this?

Why are you using .Result to unpack the result? It's a lot better to use await to get the result from an async method.
.Result can cause a deadlock if you are not being careful with the context.
Stephen Cleary has a really nice articles that goes into more details.
Don't Block on Async Code

Related

Xamarin.Forms - HttpClient GetAsync or PostAsync sometimes takes too long

I am using Xamarin.Forms and I am using HttpClient GetAsync and PostAsync to make calls to an api, my problem is the client is complaining that the application is too slow when it makes an api call. Is there anyways I can speed up this process or is there another faster way to call an api? Here is an example method:
public async Task<List<SubCatClass>> GetSubCategories(int category)
{
var client = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("category", category.ToString())
});
var response = await client.PostAsync(string.Format("https://exmample.com/api/index.php?action=getSubCategories"), content);
var responseString = await response.Content.ReadAsStringAsync();
List<SubCatClass> items = JsonConvert.DeserializeObject<List<SubCatClass>>(responseString);
return items;
}
And here is how I am calling it.
await webService.GetSubCategories(item.categoryid);
The api I have full control over the code (PHP) and the server.
Any help would be much appreciated.
Thanks in advance.
UPDATE
I called the api in postman and here was the results
You can try using ModernHttpClient, it will increase your speed than using default by Xamarin

Calling Asp.Net Web API endpoint from Azure function

I am trying to develop following scenario using Azure functions.
I have developed Asp.Net Web API which handles the Database related operation. Now, I want to implement a scheduler like functionality which will run once a day and will clean up junk data from database. I've created an endpoint for that in my Web API but I want to execute it on regular basis so I think to implement scheduler using Azure function's TimerTrigger function, is there any way to call my web api's endpoint in TimerTrigger function.
How to handle my api's authentication in Azure function?
Thanks
Update:
Based on mikhail's answer, finally I got the token using following code:
var client = new HttpClient();
client.BaseAddress = new Uri(apirooturl);
var grant_type = "password";
var username = "username";
var password = "password";
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", grant_type),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
var token = client.PostAsync("token", formContent).Result.Content.ReadAsAsync<AuthenticationToken>().Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.token_type, token.access_token);
var response = await client.GetAsync(apiendpoint);
var content = await response.Content.ReadAsStringAsync();
Azure Function is running in a normal Web App, so you can do pretty much anything there. Assuming you are on C#, the function body might looks something like
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
You may be better off putting the entire database cleanup logic in the function and making it timer triggered, that way you keep your API out of it altogether.

WebClient - UploadValues : Get Status Response

I'am trying to pass values from a controller to another controller in another domain. I'am adding data to a NameValueCollection and pass it to another controller [httppost] method and receiving data there mapped to a Model same as i passed from.
Currently i'am running it locally by opening two instance of VS simultaneously. When the both VS is opened the values are passed correctly and the information is written to db correctly and i receive a response like "{byte[0]}". Now when i try stopping the destination controller Project and try to submit data then it wont work but still i get the same response as "{byte[0]}". Can somebody please help me how to return the response command in this scenario. Is there a way a understand the UploadValues are completed or not completed.
.........
.........
NameValueCollection resumeDetails = new NameValueCollection();
resumeDetails.Add("FirstName", "KRIZTE");
byte[] res = this.Post(ConfigurationManager.AppSettings["RedirectionUrl"].ToString(), resumeDetails);
return View("Index");
}
public byte[] Post(string uri, NameValueCollection resumeDetails)
{
byte[] response = null;
WebClient client = new WebClient();
response = client.UploadValues(uri, resumeDetails);
return response;
}
You should not use the WebClient because of problems like this.
Microsoft implemented HttpClient class as a newer API and it has these benefits:
HttpClient is the newer of the APIs and it has the benefits of
has a good async programming model
1- being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
2- is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
3- also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.
so I'm gonna show you an example of using HttpClient:
var uri = "http://google.com";
var client = new HttpClient();
try
{
var values = new List<KeyValuePair<string, string>>();
// add values to data for post
values.Add(new KeyValuePair<string, string>("FirstName", "KRITZTE"));
FormUrlEncodedContent content = new FormUrlEncodedContent(values);
// Post data
var result = await client.PostAsync(uri, content);
// Access content as stream which you can read into some string
Console.WriteLine(result.Content);
// Access the result status code
Console.WriteLine(result.StatusCode);
}
catch(AggregateException ex)
{
// get all possible exceptions which are thrown
foreach (var item in ex.Flatten().InnerExceptions)
{
Console.WriteLine(item.Message);
}
}

Async methods doesn't seem to work on Windows Phone

I have the following piece of code (WPF, Windows Phone 8.1):
HttpClient client = new HttpClient();
var httpResult = client.GetAsync(feed.Url, ct);
string feedData = await httpResult.Result.Content.ReadAsStringAsync();
var sf = new SyndicationFeed();
sf.Load(feedData);
I'm trying to debug this code. However, after the line:
string feedData = await httpResult.Result.Content.ReadAsStringAsync();
debugger seems to let application run on its own and never reaches the next line. Why is that? Am I doing something wrong?
Depending on if you are calling result or wait on the task somewhere upstream, this can result in a deadlock as noted in Stephen Cleary's blog post.
Mitigate this by awaiting the client.GetAsync() and use ConfigureAwait where possible to minimize chances of deadlocks:
HttpClient client = new HttpClient();
var httpResult = await client.GetAsync(feed.Url, ct).ConfigureAwait(false);
string feedData = await httpResult.Content.ReadAsStringAsync().ConfigureAwait(false);
var sf = new SyndicationFeed();
sf.Load(feedData)

Simple HTTP POST in Windows Phone 8

I have a string that I need to POST in Windows Phone 8. It looks like this:
https://www.scoreoid.com/api/getPlayers?api_key=[apiKey]&game_id=[gameID]&response=xml&username=[username]&password=[password]
This string simply returns another string (that is formatted as XML that I parse later in my code).
I have yet to find a simple solution to this like in Windows 8.
Edit: Found the solution to my problem with an assist from rciovati and the HttpClient library.
Here's my simple code:
var httpClient = new HttpClient();
return await httpClient.GetStringAsync(uri + "?" + post_data);
Using the new Http Client Library is quite easy:
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("api_key", "12345"),
new KeyValuePair<string, string>("game_id", "123456")
};
var httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
You can find other informations about this library here.
Here's a pretty useful blog post from Andy Wigley about how to do Http networking on Windows Phone 8. The WinPhoneExtensions wrapper library he speaks of basically simulates the async/await model of network programming you can do in Win8.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx

Categories

Resources