Xamarin Forms app, HttpClient seemingly caching responses FOREVER - xamarin

I'm in the testing phase of my first Xamarin.Forms app, which relies heavily on the HttpClient to retrieve JSON data from a remote site. I've found that once a request has been made, the response seems to be cached and updated data is never retrieved. I'm initializing the HttpClient like this:
new HttpClient()
{
Timeout = new TimeSpan(0, 0, 1, 0),
DefaultRequestHeaders =
{
CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"),
Pragma = { NameValueHeaderValue.Parse("no-cache")}
}
}
Those request headers didn't seem to help at all. If I put one of the URLs in my browser, I get the JSON response with the updated data. The server side is setting a no-cache header as well.
Any idea how I can FORCE a fresh request each time? TIA. This testing is being done in an Android emulator, btw. I don't know yet whether the iOS build is behaving similarly.

I'd suggest you use the modernhttpclient nuget package, and implement your android code like:
var httpClient = new HttpClient(new NativeMessageHandler());
This code works on both android, iOS and/or code in a PCL. Basically this nuget package makes sure that you are using the latest platform optimizations for the HttpClient. For Android this is the OkHttp-package, for iOS this is NSURLSession.
This helps you prevent any of the quirks of the provided HttpClient class, and use the optimizations that the platform you're running offers you.
Issues like the one you show should no longer happen.

Related

Xamarin.Auth - Google authentication won't open in browser

I'm trying to do authentication on my Android application using Xamarin.Auth. Some time ago, Google made the policy that you cannot do this in an embedded web view (for totally valid reasons).
I'm trying to open the account authentication page in a browser, but keep getting the embedded web view. I understand that isUsingNativeUI needs to be true in the following code:
_auth = new OAuth2Authenticator(clientId, string.Empty, scope,
new Uri(Constant.AuthorizeUrl),
new Uri(redirectUrl),
new Uri(Constant.AccessTokenUrl),
null,
isUsingNativeUI = true);
At every point in my application, this always equals true.
Elsewhere, I have code that redirects to what should be a browser:
var authenticator = Auth.GetAuthenticator();
Intent intent = authenticator.GetUI(this);
this.StartActivity(intent);
Regardless, I keep getting a dreaded 403 disallowed_useragent error whenever I try to run the project. Is there another element to this that I'm missing?
To my knowledge, setting auth.IsUsingNativeUI = true in the constructor should dictate that it must open in a browser. I've been following this example to try and debug with no success. I even pulled the guy's repo down to my machine and ran it - the Intent variable at the moment of redirection is almost identical.
Could there be something stupid that I'm missing? What else might be going wrong?
I realize this is an old question, but I had the same issue.
You have to install version 1.5.0.3 of the Xamarin.Auth Nuget package. The newest one (version 1.7.0 right now) doesn't work. You'll have to also install the PCLCrypto nuget package in order to get that version to work.

Using HttpClient to make a call within a Web API

I've been working on a .NET 4.6.1 Web API project. As part of this project, I need to call another Web API and I want to use the HttpClient to do so.
From my research online, you can't rely on just doing a normal HttpClient within a using clause as it doesn't garbage collect correctly and can lead to memory leaks.
E.g., I'm currently using it as follows:
using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(CONTENTFUL_TIMEOUT_IN_SECONDS) } )
{
responseText = await client.GetStringAsync(uri).ConfigureAwait(continueOnCapturedContext:false);
}
But as suggested in other articles from Stack Overflow and others, this leads to memory leaks, and the way around this is to share a single instance of the HttpClient.
E.g., check HTTPCLIENT DESTABILIZING YOUR SOFTWARE and HttpClientHandler/HttpClient Memory Leak.
I'm not sure however how to setup a shared "single" instance of the HttpClient from within an WebAPI itself?
You should have a look on how to implement singleton pattern. Refer to this.
Then you can create a singleton of HttpClient and make it responsible for all HTTP calls from your API.

iOS Httpclient cannot connect: {System.Threading.Tasks.TaskCanceledException}

I'm building an app with Xamarin Forms. I have no issues with Android, but when I attempt to simulate or deploy the iOS app, my HttpClient can't seem to connect to the server. After the timeout expires, I get a TaskCanceledException.
The HttpClient is actually used in a separate project that is referenced by the iOS app, if that matters. Here's my usage:
string serviceUri = service + methodName;
HttpRequestMessage request = new HttpRequestMessage(methodRequestType, serviceUri)
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
};
HttpResponseMessage response = await _client.SendAsync(request).ConfigureAwait(false);
string returnString = await response.Content.ReadAsStringAsync();
return returnString;
I'm not using any waits or accessing .Result, as I've seen many people try that don't understand async operations.
I've seen older posts (circa 2013) where the wrong HttpClient is used. Is this still an issue in current releases? I've also tried changing the HttpClient implementation in the iOS project settings, to no avail.
Thanks in advance!
The issue was an invalid Deployment Target - It was set to "80" instead of "8.0
In come cases, the build server does not communicate this invalidity back to your machine - hence why it took so long to notice it!

Can't call Web api from Xamarin

I'm trying to make a simple web api call using HttpClient in an iOS build. When setting the client.BaseAddress, the BaseAddress always ends up null. I can't find what could possibly be wrong.
using System.Net.Http;
....
private const string BaseApiUrl = "http://localhost:55904/";
static HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BaseApiUrl);
// client.BaseAddress is still null
I downloaded a sample non-Xamarin project and the same code works fine.
Any ideas?
Update
As I continue messing with this I figured I would try some of the other platforms. UWP seems to work fine. I was going to test Android but all of a sudden, I have a bunch of "The name 'InitializeComponent' does not exist in the current context" errors.
I'm new to Xamarin but not to VS or C#.
Update
I was just thinking, does iOS need to request any special permission for internet access? If so, where would that be set?
Just in case anyone else comes across this problem, I found the cause. It turns out that the iOS project didn't include a reference to System.Net.Http. Once I added the reference, everything worked fine.

Visual Studio android emulator httprequest fails

So I've been working on a xamarin PCL project targeting android and windows store app and I've had this issue for about two weeks now. One of the very first things this app does is to make an http request to a yahoo service when the user tries to search for something.
Now, on the windows store app project, this works just fine. However, whenever I'm debugging the android project, this fails miserably. It times out and I get a TaskAbortedException.
I've navigated with the browser within the android emulator to the restful service url and I do get a response in the browser but nothing when I make the http request. I have tried everything I could think of but no cigar. I have researched this for weeks now and I have yet to find an answer. It should be noted that I'm making the request within the PCL project with HttpClient.
Here's the code where this happens:
var queryUrl = string.Format(QUERY_URL_TEMPLATE, TickerSearch);
try
{
var requestTask = httpClient.GetStringAsync(queryUrl);
requestTask.ContinueWith(t =>
{
var responseDto = JsonConvert.DeserializeObject<TickerSearchResultDto>(t.Result);
TickerSearchResults = responseDto.ResultSet.Result;
});
}
catch (Exception ex)
{
}
Any help is greatly appreciated.

Resources