7

Thanks for your attention. I'm trying to make a Xamarin.Forms App that communicates with a REST API. The API is fully functional, I've tested it with Postman and another WPF project. Upon trying to call a simple GET method with my HttpClient, I get the following HttpResponseMessage

{
    StatusCode: 400, 
    ReasonPhrase: 'Bad Request', 
    Version: 1.1, 
    Content: System.Net.Http.StreamContent, 
    Headers:
    {
        Server: Microsoft-HTTPAPI/2.0
        Date: Sun, 17 May 2020 12:20:37 GMT
        Connection: close
        Content-Type: text/html; charset=us-ascii
        Content-Length: 334
    }
}

public async Task TurnLEDOn()
{
    HttpClient Client = new HttpClient(new System.Net.Http.HttpClientHandler());

    Client.DefaultRequestHeaders.Accept.Clear();
    Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json"));
    Client.BaseAddress = new Uri("https://192.168.1.2:44341/");
    HttpResponseMessage response = await Client.GetAsync("api/ChipCore/TurnLEDOn");
    if (response.IsSuccessStatusCode)
    {
        string receivedPerson = await response.Content.ReadAsAsync<string>();
    }
}

This same code is run by a WPF program and works flawlessly.

Both my phone and Laptop are connected to the same Wi-Fi network.

  • I've allowed port 44341 through Firewall, I've even tried running the whole thing with Firewall off. The browser on my phone can't access the API. (Bad Request)
  • I have tried changing the server url from https to http but faced a trust anchor for certification path not found I have added these Permissions to android.manifest:
CHANGE_NETWORK_STATE
CHANGE_WIFI_STATE
ACCESS_NETWORK_STATE
INTERNET

Method in API

[RoutePrefix("api/ChipCore")]
public class ValuesController : ApiController
{
    [HttpGet]
    [Route("TurnLEDOn")]
    public bool TurnLEDOn()
    {
        return Switch.TurnLEDOn();
    }
}

Update

  • I have tried bypassing the Certificate by adding this line to MainActivity.cs

    ServicePointManager.ServerCertificateValidationCallback += (o, cert, chain, errors) => true;

  • I have tired putting in the URL in my phones browser, I get Error 400 - Bad Request

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
Sadra M.
  • 1,304
  • 1
  • 17
  • 28
  • 2
    what happens if you simply browse `https://192.168.1.2:44341/api/ChipCore/TurnLEDOn` from the phone? – Frank Nielsen May 17 '20 at 13:09
  • 1
    You can bypass the certificate error by using the approach described in this link. I believe you need to configure https correctly to make it work with https: https://forums.xamarin.com/discussion/91782/trust-anchor-for-certification-path-not-found check the following link on how to configure https on .Net Core: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/certauth?view=aspnetcore-3.1 – Elton Santana May 17 '20 at 14:12
  • 1
    Can you answer the question that @FrankNielsen had asked? – Tarun Lalwani May 19 '20 at 14:33
  • "I have tired putting in the URL in my phones browser, I get Error 400 - Bad Request" Is in the question itself @TarunLalwani – Sadra M. May 20 '20 at 11:09
  • This site is about coding problems. Your problem is not of that type, it is that your phone cannot connect to some local server. The question should be closed but it has a bounty so it seems that it can't be. – Ivan Ičin May 23 '20 at 09:14

4 Answers4

2

IIS Express cannot process requests from other machines.

You can:

Jim W
  • 4,866
  • 1
  • 27
  • 43
0

Try the following solution.

  1. Right Click Android Project -> Android Options -> Advanced -> Change HttpClientimplementation from Default to Android

Refer to: Xamarin Forms - simple PostAsync() returns error 400 bad request

.

  1. If this solution doesn't work you can try to execute the code that the error occurs only when HttpResponseMessage.IsSuccessStatusCode is satisfied.
if (Resultado.IsSuccessStatusCode)
{
    //
}

Refer to: https://forums.xamarin.com/discussion/comment/391413/#Comment_391413

.

  1. If both of the solutions does not work you can try going to this similar question for more answers
amitklein
  • 1,302
  • 6
  • 23
  • 1
    1) I checked the Options set on my android project, HttpClient implementation was already set to Android. 2) I am already doing this, it even shows up on the code I've put up on my question. 3) The link you have provided is a reference to someone with a slightly different problem. They are able to establish a connection in their scenario. But not when a "Foreign key" is added to one of their model Classes. Thanks for the time you put in though. – Sadra M. May 23 '20 at 19:28
0

The problem looks like your phone is not connected to your server (which is hosted on your computer).

If you are able to access this same request using Postman, it shouldn't be a problem but let's find out.

Step 1) What do your server logs say? When your phone throws a 400 bad request error, did it really even connect to your computer? Just go to your server logs and find out whether was it even hit? If the server was hit, then go to step 2. Else go to step 3 for one more confirmation.

Step 2) Can you compare the request made through postman with the request made through your phone? Both the header and the body? Or with the WPF request? You need to find out what's the different because something definitely is.

Step 3) Can you try one more thing. Just create a new controller at root "/" and send a "Hello world" string in response. Now try accessing the root through your phone and postman. You can directly open it in your phone browser. If it doesn't say "Hello world" then it's confirmed that nothing is wrong with your api but a connection issue b/w your phone and computer.

DeityWarrior
  • 716
  • 1
  • 6
  • 5
0

assuming that you are running IIS Express in debug mode, it won't allow any connection from outside your computer, I've had the same problem with a WebAPI before

you may wanna try to run your app in a VM or something you should also try accessing the API from another computer, you can test it using your ready WPF app, i believe you'll face the same problem then

you could also try to send postman requests using the Server IP address instead of localhost

If you happen to reproduce the problem this way then all you need is to configure the IIS to server remote/external traffic

Massaynus
  • 322
  • 2
  • 9