Can't call Web api from Xamarin - asp.net-web-api

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.

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.

Xamarin Forms app, HttpClient seemingly caching responses FOREVER

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.

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!

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.

MvvmLight's SimpleIoc breaking in Xamarin Forms 1.3 Android and iOS app, but not in Windows Phone

I am working on a Xamarin Forms app and all is going well with the Windows Phone building and running. However when I try and run the Android version, it build OK and then fails and I get an exception when calling the ServiceLocator to resolve ViewModel in the ViewModelLocator.
Breaks on the line in the ViewModelLocator
return ServiceLocator.Current.GetInstance<MainViewModel>();
with
System.Reflection.TargetInvocationException
Source "mscorlib" string
StackTrace "at System.Reflection.MonoMethod.Invoke (object,System.Reflection.BindingFlags,System.Reflection.Bind…"
and hovering over the 'GetInstance' shows
Could not resolve type: global::Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<global::hms.BillSplitter.ViewModel.PCL.MainViewModel>
My ViewModel's only constructor looks like
public MainViewModel(INavigationService navigationService, ICountryTippingService countryTippingService, AppSettings appSettings)
{
_navigationService = navigationService;
_countryTippingService = countryTippingService;
ThisAppSettings = appSettings;
ThisBillDetail = new BillDetail();
ThisBillDetail.TotalOnBill = 0;
}
All dependencies are registered ahead of this in the ViewModelLocator e.g.
SimpleIoc.Default.Register(() => new HmsPublicCoreMobileServiceClient(HmsCommonSettingConstants.HmsPublicCoreServiceUrl, HmsCommonSettingConstants.HmsPublicCoreServiceAppKey));
var prefService = ServiceLocator.Current.GetInstance<IPreferenceService>();
SimpleIoc.Default.Register(() => (SettingsHelper.GetCurrentSettings(prefService)));
SimpleIoc.Default.Register<MainViewModel>();
and some platform specific ones in the MainActivity.cs (Android) and AppDelegate(iOS) e.g.
SimpleIoc.Default.Register(() => new PreferenceService(this));
What I don't get is that it work beautifully in Windows Phone? What is it about Android that's different? Has anyone used SimpleIoc in Xamarin 1.3+?
Should I use a factory to create he ViewModel?
Any help would be great and much appreciated. I am using all the latest versions for MVVMLight (5.1.0.1) and Xamarin (1.3.3).
I finally worked out what the problem was and it's pretty basic and nothing to do with MvvmLight and/or Xamarin Forms updates!
I made the mistake of Registering a concrete class in a factory and then attempted to GetInstance on an Interface. SimpleIoC was not able to reconcile it.
from the code above
SimpleIoc.Default.Register(() => (SettingsHelper.GetCurrentSettings(prefService)));
should have been
SimpleIoc.Default.Register<IPreferenceService>(() => (SettingsHelper.GetCurrentSettings(prefService)));
so that the line
var prefService = ServiceLocator.Current.GetInstance<IPreferenceService>();
would know what I was talking about.
Anyhow, if you get errors like this, you'll know what to look for!!

Resources