Invalid URI: Invalid port specified when url has m

2019-05-11 14:32发布

问题:

I am using dnsdynamic.org to point to my personal website hosted at my home. My home ip will be frequently changing once a month. dnsdynamic.org provide a web method call to update ip.

https://username:password@www.dnsdynamic.org/api/?hostname=techno.ns360.info&myip=127.0.0.1

When I call this through browser it works perfect. When I try to call this through c# code it throws the following exception.

Invalid URI: Invalid port specified.
    at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
    at System.Net.WebRequest.Create(String requestUriString)

Since there is a colon in the url it looks like system.uri try to parse my password as integer.

I tried adding a port after .org

https://username:password@www.dnsdynamic.org:443

no luck with this.

could someone please point me how to resolve this error.

I tried with don't escape and escape option while creating uri, still not working.

var ri = new Uri("https://username:password@www.dnsdynamic.org/api/?hostname=techno.ns360.info&myip=127.0.0.1",true);

EDIT: It looks like the username is causing the problem. My username is my email address. And my email address end with *.com. So uri is trying to parse my password.

Still no solution found to overcome this issue. I can't change my username since dnsdyanmic.org use the email address as username.

回答1:

If you're using an HttpWebRequest to make the reqeust, you shouldn't include the credentials in the URI (as you can tell, it's invalid).

You should instead add the credentials to the HttpWebRequest and let it handle passing them through:

// Only broke this up for readability
var uri = new Uri("https://www.dnsdynamic.org/api/?hostname=techno.ns360.info" + 
                  "&myip=127.0.0.1", true);
var cache = new CredentialCache();
cache.Add(uri, "Basic", new NetworkCredential("username", "password"));

var request = WebRequest.Create(uri);
request.Credentials = cache;