Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient with BaseAddress

I have a problem calling a webHttpBinding WCF end point using HttpClient and the BaseAddress property.

HttpClient

I created a HttpClient instance specifying the BaseAddress property as a local host endpoint.

enter image description here

GetAsync Call

I then call the GetAsync method passing in the additional Uri inforamtion.

HttpResponseMessage response = await client.GetAsync(string.Format("/Layouts/{0}", machineInformation.LocalMachineName())); 

enter image description here

Service endpoint

[OperationContract] [WebGet(UriTemplate = "/Layouts/{machineAssetName}", ResponseFormat = WebMessageFormat.Json)] List<LayoutsDto> GetLayouts(string machineAssetName); 

Problem

The problem I am having is that the is that /AndonService.svc part of the BaseAddress is being truncated so the resultant call goes to https://localhost:44302/Layouts/1100-00277 rather that https://localhost:44302/AndonService.svc/Layouts/1100-00277 resulting in a 404 Not Found.

Is there a reason the BaseAddress is being truncated in the GetAsync call? How do I get around this?

like image 491
Phil Murray Avatar asked Dec 16 '13 10:12

Phil Murray


People also ask

How do I set HttpClient BaseAddress?

If you would rather work with relative URLs than absolute URLs you can use the BaseAddress property of the HttpClient. All you have to do is set the BaseAddress on the HttpClient: var httpClient = new HttpClient(); httpClient.

What is base address in API?

The base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.

What is base address in URL?

The URL found in the address bar of the front page of a website is its base URL. In other words, the common prefix found while navigating inside a given website is known as the base URL.


Video Answer


1 Answers

In the BaseAddress, just include the final slash: https://localhost:44302/AndonService.svc/. If you don't, the final part of the path is discarded, because it's not considered to be a "directory".

This sample code illustrates the difference:

// No final slash var baseUri = new Uri("https://localhost:44302/AndonService.svc"); var uri = new Uri(baseUri, "Layouts/1100-00277"); Console.WriteLine(uri); // Prints "https://localhost:44302/Layouts/1100-00277"   // With final slash var baseUri = new Uri("https://localhost:44302/AndonService.svc/"); var uri = new Uri(baseUri, "Layouts/1100-00277"); Console.WriteLine(uri); // Prints "https://localhost:44302/AndonService.svc/Layouts/1100-00277" 
like image 78
Thomas Levesque Avatar answered Oct 07 '22 20:10

Thomas Levesque