0

Im trying to consume an asp.net core Post api using the MVVM so I created a startup class who have the base url and this service class to consume the api :

    public class ApiMachineService :ImachineService
    {
        private readonly HttpClient _httpClient;
        public ApiMachineService(HttpClient _httpClient)
        {
            _httpClient = new HttpClient();
        }


        public async Task AddMachine(Machine machine)
        {
            var response = await _httpClient.PostAsync("Machine/creation",
                           new StringContent(JsonSerializer.Serialize(machine), Encoding.UTF8, "application/json"));

            response.EnsureSuccessStatusCode();
        }

And I created a simple Xaml page who have two entry and a button who binding the add command in this viewModel class:

   public class ajoutVM : BaseViewModel
    {
        private readonly ImachineService _MachineService;
        public string nom;
        public string Qr;
    public ajoutVM (ImachineService machineService)
        {
        _MachineService = machineService;
        ajout = new Command(async () => await SaveMachine());
        }
        public async Task SaveMachine()
        {
            try
            {
                var machine = new Machine
                {
                    Machine_Name = Machine_Name,
                    Machine_Qr = Machine_Qr

                };

                await _MachineService.AddMachine(machine);

                await Shell.Current.GoToAsync("..");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public string Machine_Name { get => nom; set { nom = value; NotifyPropertyChanged(nameof(nom)); } }
     
        public string Machine_Qr { get => Qr; set { Qr = value;NotifyPropertyChanged(nameof(Qr)); } }
      
        public ICommand ajout { get; }

    }

the startup class:

  public static class Startup
    {
        private static IServiceProvider serviceProvider;
        public static void ConfigureServices()
        {
            var services = new ServiceCollection();
            //add services
            services.AddHttpClient<ImachineService, ApiMachineService>(c => 
            {
                c.BaseAddress = new Uri("http://192.168.1.114:45457/api");
                c.DefaultRequestHeaders.Add("Accept", "application/json");
            });

            //add viewmodels
            services.AddTransient<ajoutVM>();

            serviceProvider = services.BuildServiceProvider();
        }
         public static T Resolve<T>() => serviceProvider.GetService<T>();

    }

But while debugging the application, when I pressed the add button I got this message in the debugger output:

[monodroid] Not wrapping exception of type Java.IO.IOException from method SendAsync. This will change in a future release. Java.IO.IOException: Cleartext HTTP traffic to 192.168.1.114 not permitted at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <1921523bc22e407fa9a0855bdae29335>:0 at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractVoidMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x00014] in <1921523bc22e407fa9a0855bdae29335>:0 at Java.Net.HttpURLConnectionInvoker.Connect () [0x00000] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-31/mcw/Java.Net.HttpURLConnection.cs:725 at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass44_0.b__0 () [0x0007d] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:356 at System.Threading.Tasks.Task.InnerInvoke () [0x0000f] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2476 at System.Threading.Tasks.Task.Execute () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2319 --- End of stack trace from previous location where exception was thrown --- at Xamarin.Android.Net.AndroidClientHandler.DoProcessRequest (System.Net.Http.HttpRequestMessage request, Java.Net.URL javaUrl, Java.Net.HttpURLConnection httpConnection, System.Threading.CancellationToken cancellationToken, Xamarin.Android.Net.AndroidClientHandler+RequestRedirectionState redirectState) [0x000e4] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:405 at Xamarin.Android.Net.AndroidClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00286] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Xamarin.Android.Net/AndroidClientHandler.Legacy.cs:287 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:506 at ADD.Services.ApiMachineService.AddMachine (ADD.Models.Machine machine) [0x00045] in C:\Users\amyra\source\repos\ADD\ADD\Services\ApiMachineService.cs:22 at ADD.ViewModels.ajoutVM.SaveMachine () [0x00072] in C:\Users\amyra\source\repos\ADD\ADD\ViewModels\ajoutVM.cs:33 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSourcJava.IO.IOException stack trace --- java.io.IOException: Cleartext HTTP traffic to 192.168.1.114 not permitted at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:124) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)

Gazdallah Amira
  • 188
  • 3
  • 16
  • "nothing happened" is not a useful description of the problem. Have you verified that your code is executing? Have you traced it to determine where specifically it is hung or encountering an error? Are you getting any errors or exceptions? – Jason May 27 '22 at 12:30
  • @Jason I'm new in Xamarin, I don't know how to trace the code. No I didn't got any error or exeption but when executing the command nothing added in the dataBase. – Gazdallah Amira May 27 '22 at 13:37
  • You need to learn how to use the debugger. https://learn.microsoft.com/en-us/xamarin/android/deploy-test/debugging/ – Jason May 27 '22 at 13:49
  • 1
    you can also use some simple logging - add `Console.Writeline()` statements to your code so you can see from the `Application Output` window where the execution reaches – Jason May 27 '22 at 15:54
  • 1
    I don't see any new useful information. Have you still not determined which line causes the exception? Are you **positive** that `_MachineService` is not null? That seems like the most likely culprit – Jason May 27 '22 at 22:18
  • 1
    Instead of logging `ex.Message`, try logging the entire `ex` (or `ex.ToString()`). That will give you a stack trace that tells you the exact line of code where exception happened. – StriplingWarrior May 27 '22 at 22:19
  • @Jason the exception is in this line in the ApiMachineService: var response = await _httpClient.PostAsync("Machine/creation", new StringContent(JsonSerializer.Serialize(machine), Encoding.UTF8, "application/json")); – Gazdallah Amira May 27 '22 at 22:41
  • You have a parameter and a local variable both named _httpClient. Try renaming one of them – Jason May 27 '22 at 22:45
  • @jason I updated the question again it have more details on the exception – Gazdallah Amira May 27 '22 at 22:48
  • OK, backup. The **very first line** of the exception tells you exactly what the problem is. "System.InvalidOperationException: An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set". You are not providing a valid url,. – Jason May 27 '22 at 22:48
  • "Machine/creation" is not a valid url – Jason May 27 '22 at 22:49
  • @Jason no it's the right url – Gazdallah Amira May 27 '22 at 22:51
  • Please read the message. "The request URI must either be an absolute URI or BaseAddress must be set". An absolute URI is http://some.valid.uri/path". You are not setting `BaseAddress` so you must provide a absolute URI. – Jason May 27 '22 at 22:56
  • @jason have you some resorces for doing that – Gazdallah Amira May 27 '22 at 23:00
  • a resource for what? You don't know how to build a url to your own service? `http://my.server.name/Machine/creation`? – Jason May 27 '22 at 23:03
  • @jason no I did that before in the startup class! I will update the question to add the startup class – Gazdallah Amira May 27 '22 at 23:05
  • Your constructor creates a new instance of HttpClient. It doesn’t matter what you set in some other class – Jason May 27 '22 at 23:16
  • @jason can you more explain this please Im new in Xamarin and dotnet plateforme – Gazdallah Amira May 27 '22 at 23:21
  • 1
    In PostAsync just use the full url for your service endpoint. This has taken far too long for such a basic error. – Jason May 27 '22 at 23:23
  • @jason thank you a lot from all my heart you are really an amazing person!! but even when I did all of that it still doesn't work. – Gazdallah Amira May 27 '22 at 23:29
  • As I noted before, "does not work" is not really a useful description of the problem. I suspect that you have multiple issues with your code - it is very difficult to try to direct you how to debug them when you do not know how to use the debugger. Do you get a response code from the request? Does it timeout, or give an error or exception? – Jason May 27 '22 at 23:35
  • @jason yes you are right i understand that! I will update the exception right now – Gazdallah Amira May 27 '22 at 23:45
  • 1
    Google “usecleartexttraffic”. There is a config setting in the manifest you can set – Jason May 28 '22 at 00:02

0 Answers0