2

我尝试构建以下 uri

http://localhost:8080/TestService.svc/RunTest

我这样做如下

var uriBuilder = new UriBuilder();
uriBuilder.Host = "localhost:8080/TestService.svc";
uriBuilder.Path = String.Format("/{0}", "RunTest");
string address = uriBuilder.ToString()

//In debugger the address looks like http://[http://localhost:8080/TestService.svc]/RunTest
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(address);

以上生成异常

Invalid URI: The hostname could not be parsed.

感谢您帮助解决问题

4

2 回答 2

2

使用 Uri 构建器时,您需要将主机、端口和路径作为它自己的行。此外,TestService.svc 也是路径的一部分,而不是主机,如果不使用端口但必须将端口分开,您可以摆脱它。

var uriBuilder = new UriBuilder();
uriBuilder.Host = "localhost";
uriBuilder.Port = 8080;
uriBuilder.Path = String.Format("/{0}/{1}", "TestService.svc", "RunTest");
var address = uriBuilder.ToString();
于 2014-11-04T13:47:22.567 回答
1

当我运行您的代码时,我还看到方括号作为address变量的值,正如您指出的那样,但我没有PerfTestService在生成的 Uri 中看到,也看不到为什么会这样?!我懂了:

http://[localhost:8080/TestService.svc]/RunTest

由于您已经知道主机和路径,我建议您将其构造为字符串。

 var uriBuilder = new UriBuilder("http://localhost:8080/TestService.svc/RunTest");
 string address = uriBuilder.ToString();
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
于 2014-11-04T09:24:12.500 回答