我在调用 方法传入额外的 Uri 信息.
HttpResponseMessage response = await client.GetAsync(string.Format("/Layouts/{0}", machineInformation.LocalMachineName()));服务端点
[操作契约][WebGet(UriTemplate = "/Layouts/{machineAssetName}", ResponseFormat = WebMessageFormat.Json)]列表GetLayouts(string machineAssetName);问题
我遇到的问题是 BaseAddress 的 /AndonService.svc 部分被截断,因此结果调用转到 localhost:44302/Layouts/1100-00277 而不是 localhost:44302/AndonService.svc/Layouts/1100-00277 导致 404 Not Found.
是否有原因在 GetAsync 调用中截断了 BaseAddress?我该如何解决这个问题?
解决方案在 BaseAddress 中,只包含最后一个斜杠:localhost:44302/AndonService.svc/.如果不这样做,路径的最后一部分将被丢弃,因为它不被视为目录".
此示例代码说明了不同之处:
//没有最后的斜线var baseUri = new Uri("localhost:44302/AndonService.svc");var uri = new Uri(baseUri, "Layouts/1100-00277");Console.WriteLine(uri);//打印localhost:44302/Layouts/1100-00277"//最后的斜线var baseUri = new Uri("localhost:44302/AndonService.svc/");var uri = new Uri(baseUri, "Layouts/1100-00277");Console.WriteLine(uri);//打印localhost:44302/AndonService.svc/Layouts/1100-00277"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.
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()));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 localhost:44302/Layouts/1100-00277 rather that 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?
解决方案In the BaseAddress, just include the final slash: 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("localhost:44302/AndonService.svc"); var uri = new Uri(baseUri, "Layouts/1100-00277"); Console.WriteLine(uri); // Prints "localhost:44302/Layouts/1100-00277" // With final slash var baseUri = new Uri("localhost:44302/AndonService.svc/"); var uri = new Uri(baseUri, "Layouts/1100-00277"); Console.WriteLine(uri); // Prints "localhost:44302/AndonService.svc/Layouts/1100-00277"
更多推荐
带基地址的 HttpClient
发布评论