cvdev
cvdev

Reputation: 21

'An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.'

I am trying to consume REST API from a xamarin forms app using the following code. however for some strange reason I am getting Invalid URI Error. I also tried using an Absolute Path in the PostAsync Method but still the error persists. Can someone guide me on this please?

HttpClient client = new HttpClient(); 
string baseAdd = @"http://localhost:9000/";

    public async void GenerateAPIToken()
    {

        string tsResult = "";
        try
        {

            Token token = new Token();
            //GET TOKEN
            client.BaseAddress = new Uri(baseAdd);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage msg = new HttpRequestMessage();
            msg.Content = new StringContent(@"{""username"":""admin"",""password"":""admin123""}");


            HttpResponseMessage response = await client.PostAsync(client.BaseAddress+"token/generate.php", msg.Content);


            if (response.StatusCode == HttpStatusCode.OK)
            {
                HttpContent cnt = response.Content;
                tsResult = await cnt.ReadAsStringAsync();
                token = JsonConvert.DeserializeObject<Token>(tsResult);
                App.apiToken = token.Document.AccessToken;
            }

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

    }

Upvotes: 2

Views: 11316

Answers (1)

Uri Y
Uri Y

Reputation: 850

It looks like you're setting the BaseAddress, and sending an absolute URI. When the BaseAddress is set, it is being added as a prefix to the URI. You must either set the BaseAddress and send a relative URI, or send an absolute URI without setting the base address. see https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.baseaddress?view=netcore-3.1

Upvotes: 2

Related Questions