Search code examples
c#urihttprequesturibuilder

Use UriBuilder and construct httpRequest


I try to build the following uri

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

I do it as following

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);

The above generates an exception

Invalid URI: The hostname could not be parsed.

I`ll appreciate your help in solving the issue


Solution

  • When using the Uri builder you need to put the host, port & path as it's own line. Also TestService.svc is also part of the path and not the host, you can get away with it if not using port but with port they have to be separated out.

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