Problems accessing a web api in a Xamarin Forms project

Asked

Viewed 327 times

0

On my first screen of mine app mobile what I’m doing is the screen of Login, but whenever I try to log the return is

Statuscode: 404,

Reasonphrase: 'Not Found'

I have confirmed and the uri is correct, access via Postman normally, I began to suspect that it is something lacking to configure in the project or manifest of app, I already tested the project Android and UWP, all give the same problem.

What gave me this certainty is that I created a console app just to test access to api, everything works normally, follows the code:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Net.Http;

namespace app1
{
    class Program
    {
        static void Main(string[] args)
        {
            var url = "https://api.dominio.com.br/login";
            var userName = "[email protected]";
            var password = "12345678";

            var token = GetToken(url, userName, password);
        }

        static string GetToken(string url, string userName, string password)
        {
            var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "username", userName ),
                        new KeyValuePair<string, string> ( "password", password )
                    };
            var content = new FormUrlEncodedContent(pairs);
            
            using (var client = new HttpClient())
            {
                var response = client.PostAsync(url, content).Result;
                JObject o = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                return (string)o["token"];
            }
        }
    }
}

How can I solve this problem ?

On request I will put the code that is not working, although it is the same as the code above:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace AppMobile.Services
{
    public class Auth : IAuthenticate
    {
        const string Url = "https://api.dominio.com.br/Login";
        
        public async Task<string> GetToken(string user, string pass)
        {
            var pairs = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>( "username", user ),
                new KeyValuePair<string, string> ( "password", pass )
            };
            var content = new FormUrlEncodedContent(pairs);
            using (var client = new HttpClient())
            {
                var response = await client.PostAsync(Url, content);
                JObject obj = JObject.Parse(response.Content.ReadAsStringAsync().Result);
                var token = (string)obj["token"];
                
                return token;
            }
        }
    }
}
  • If I understand correctly, this console is working, right? If so, we need the code that isn’t working to find out why. If possible, you could [Dit] your question and add this information?

  • Try to put the content like this, Jsonconvert.Serializeobject(pairs).

  • @Randrade, I put the code you asked for.

  • You specified the manifest permission on android to authorize internet access ? android.permission.INTERNET

  • Try the following on your project Android - MainActivity.cs add in the beginning method OnCreate the code ServicePointManager.ServerCertificateValidationCallback +=&#xA; (sender, cert, chain, sslPolicyErrors) => true; If it works add as a response.

  • @Juniorporpirio, I downloaded the manifest and did not find this option, but as I understood on this link here is a permission that is already included: https://developer.xamarin.com/recipes/android/general/projects/add_permissions_to_android_manifest/

  • @Marcoviniciussoaresdalalba, If I do this the content will be a string type, Postasync does not receive it, receives an Httpcontent, will not work...

  • Yes is included to authorize in android manifest. For this you must in VS right click on the Droid project and go to properties -> Android Manifest and enable INTERNET check.

  • @rubStackOverflow, put the code and gave anyway, nothing changed.

  • @rhgm you managed to perform the configuration on Android Manifest and test the application ?

  • @Juniorporpirio, already downloaded the Android Manifest and did not find this option, but I edited the Androidmanifest.xml and added: <uses-permission android:name="android.permission.INTERNET" /> Still nothing done, I’m having the same problem.

  • @rhgm, tries to put the string result into a variable with await. ex: var stringresponse = await Response.Content.Readasstringasync(); or remove async to test and call directly in the result as it did on the console.

  • @Juniorphyrus is the same error message you already informed "{\"statusCode\":404,\"error\":\"Not Found\"}"

Show 8 more comments

1 answer

0


I was able to resolve by changing the post to not run asynchronously:

var response = await client.PostAsync(Url, content).ConfigureAwait(false);

So it worked in the console application, there it was synchronous. I haven’t found anything in the documentation that explains why this should work asynchronously...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.