基于地址的 HttpClient

43
我遇到了一个问题,使用HttpClientBaseAddress属性调用webHttpBinding WCF端点时出现错误。 HttpClient 我创建了一个HttpClient实例,并将BaseAddress属性指定为本地主机端点。

enter image description here

GetAsync 调用

我接着调用 GetAsync 方法并传入额外的 Uri 信息。

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

enter image description here

服务终端点

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

问题

我遇到的问题是,基地址中的/AndonService.svc部分被截断了,因此最终的调用指向了https://localhost:44302/Layouts/1100-00277而不是https://localhost:44302/AndonService.svc/Layouts/1100-00277,导致404 Not Found错误。

为什么在GetAsync调用中会截断BaseAddress?我该如何解决这个问题?


2
可能是为什么HttpClient BaseAddress不起作用?的重复问题。 - Timothy Shields
1个回答

88
BaseAddress 中,请确保包含最后的斜线:https://localhost:44302/AndonService.svc/。如果省略,路径的最后一部分将被丢弃,因为它不被认为是一个“目录”。
下面的示例代码说明了这种差异:
// 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"

10
请查看我的问题和答案:https://dev59.com/jmAg5IYBdhLWcg3wlLqh这个答案漏掉了一个重要的细节。 - Timothy Shields

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接