带基地址的 HttpClient [英] HttpClient with BaseAddress

查看:21
本文介绍了带基地址的 HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调用 方法传入额外的 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 部分被截断,因此结果调用转到 https://localhost:44302/Layouts/1100-00277 而不是 https://localhost:44302/AndonService.svc/Layouts/1100-00277 导致 404 Not Found.

是否有原因在 GetAsync 调用中截断了 BaseAddress?我该如何解决这个问题?

解决方案

BaseAddress 中,只包含最后一个斜杠:https://localhost:44302/AndonService.svc/.如果不这样做,路径的最后一部分将被丢弃,因为它不被视为目录".

此示例代码说明了不同之处:

//没有最后的斜线var baseUri = new Uri("https://localhost:44302/AndonService.svc");var uri = new Uri(baseUri, "Layouts/1100-00277");Console.WriteLine(uri);//打印https://localhost:44302/Layouts/1100-00277"//最后的斜线var baseUri = new Uri("https://localhost:44302/AndonService.svc/");var uri = new Uri(baseUri, "Layouts/1100-00277");Console.WriteLine(uri);//打印https://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 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?

解决方案

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"

这篇关于带基地址的 HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆