C# 使用UriBuilder并构造httpRequest
我尝试构建以下uriC# 使用UriBuilder并构造httpRequest,c#,uri,httprequest,uribuilder,C#,Uri,Httprequest,Uribuilder,我尝试构建以下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 d
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.
我非常感谢您帮助我解决这个问题当我运行您的代码时,我还看到方括号是您指出的
地址
变量的值,但是我在生成的Uri中没有看到PerfTestService
,我也不明白为什么会这样?!我明白了:
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);
使用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();