Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StatusCode 400 "Bad request" when Connecting a Xamarin.forms app on a physical Phone to an Asp.net REST API

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

like image 623
Cedric Moore Avatar asked May 17 '20 12:05

Cedric Moore


1 Answers

IIS Express cannot process requests from other machines.

You can:

  • Install the free extension I made called Conveyor which doesn't modify anything to do with your project or configuration https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti

  • Or, modify the configuration in IIS Express How to enable external request in IIS Express?

  • Or, host the project on IIS proper

like image 134
Jim W says reinstate Monica Avatar answered Sep 18 '22 15:09

Jim W says reinstate Monica