Home > other >  Xamarin BadRequest when connecting to localhost
Xamarin BadRequest when connecting to localhost

Time:08-26

Im having some problems to connect to my localhost API in my xamarin app on android emulator.

This is my code

public class ReservasConnection {

    private HttpClient client;

 
    private HttpClient GetLocalInstance() {

        HttpClientHandler clientHandler = new HttpClientHandler();
        clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

        HttpClient _client = new HttpClient(clientHandler);

        _client.BaseAddress = new Uri("https://10.0.2.2:44365/reservasandroid/");
        _client.DefaultRequestHeaders.Accept.Clear();
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        return _client;
    }

    public VehiculosPreciosResponse GetVehiculosPrecio(VehiculosRequest datosRequest) {

        client = GetLocalInstance();

        string datosToJson = JsonConvert.SerializeObject(datosRequest);

        var content = new StringContent(datosToJson, Encoding.UTF8, "application/json");

        HttpResponseMessage response = client.PostAsync("GetVehiculosPrecios", content).Result;

        response.EnsureSuccessStatusCode();

        var vehiculosResponse = response.Content.ReadAsStringAsync().Result;

        return JsonConvert.DeserializeObject<VehiculosPreciosResponse>(vehiculosResponse);

    }

}

When using this code I get a 400 BadRequest as response. I think the problem is with the API because we have another API and if I try to connect to the other one it works without any problem. This is the API code:

public class ReservasAndroidController : Controller
{

    string ConnectionString;
    int Minutos;

    ReservasHandler handler;

    public ReservasAndroidController() {

        ConnectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        Minutos = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Minutos"]);

        handler = new ReservasHandler();

    }

    [HttpPost]
    public JsonResult GetVehiculosPrecios(VehiculosAndroidRequest request) {
        UserConexiones usrConexiones = null;
        try {

            usrConexiones = UserConexiones.GetInstance();
            usrConexiones.AbrirConexion(ConnectionString);

            if(!LoginHandler.Validar_IdSession(request.SessionID, usrConexiones))
                return Json(new VehiculosPreciosAndResponse(2, "El token no es valido", new VehiculoPrecioAnd[0]), JsonRequestBehavior.AllowGet);

            var usuario = LoginHandler.getUserCostumer(request.SessionID, Minutos, usrConexiones);

            var vehiculos = handler.GetVehiculosPreciosAndroid(request.Datos, usuario.IdEmpresa, usrConexiones);


            return Json(new VehiculosPreciosAndResponse(1, "", vehiculos.ToArray()), JsonRequestBehavior.AllowGet);

        }catch(Exception ex) {
            ClGeneral.EscribeLog(ex);
            return Json(new VehiculosPreciosAndResponse(3, ex.Message, new VehiculoPrecioAnd[0]), JsonRequestBehavior.AllowGet);
        } finally {
            if (usrConexiones != null)
                usrConexiones.CerrarConexion();
        }
    }

}

But it doesn't even reach the API and directly get the 400 status. I think some configuration is missing in my API but I don't know what it can be. Is not a SSL problem I resolved that by using the HttpClientHandler and setting the CustomValidationCallback in it. The API that doesn't work is .NET Framework 4.8 and the one that works is .NET Framework 4.7.2. If I try to reach the API through chrome in the emulator to a test endpoint I get this:

enter image description here

But if I try to reach the test endpoint in the other API it works without any problem:

enter image description here

CodePudding user response:

Cheking the settings I've found the difference between one API and the other.

In the solution folder going to .vs/[projectName]/config is the file applicationgost.config there we find the following code:

<sites>
   ...
   <site name="[projectName]" id="2">
      ...
      <bindings>
        ...
        <binding protocol="https" bindingInformation="*:44365:localhost"/>
      </bindings>
   </site>
</sites>

In order to work with the emulator we have to change localhost to 127.0.0.1

  • Related