You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#报错‘Invalid URI: The format of the URI could not be determined’排查

解决“Invalid URI: The format of the URI could not be determined.”错误

最近我在写这段C#代码的时候,一直碰到这个错误提示:

Invalid URI: The format of the URI could not be determined.

错误正好出现在代码的第3行,我的代码如下:

public static string Get() { 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"27.**.***.14"); 
    request.MaximumAutomaticRedirections = 4; 
    request.MaximumResponseHeadersLength = 4; 
    request.Credentials = CredentialCache.DefaultCredentials; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream receiveStream = response.GetResponseStream(); 
    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); 
    string result = readStream.ReadToEnd(); 
    response.Close(); 
    readStream.Close(); 
    return result; 
}

后来仔细排查才发现,问题居然这么简单——我给的IP地址前面少了http://这个协议前缀!WebRequest.Create()方法要求传入的URI必须是完整的格式,得包含协议部分,不然它根本没法识别这是个合法的HTTP地址。

把代码改一下,在IP前面加上http://就搞定了:

public static string Get() { 
    // 补上http://协议前缀
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://27.**.***.14"); 
    request.MaximumAutomaticRedirections = 4; 
    request.MaximumResponseHeadersLength = 4; 
    request.Credentials = CredentialCache.DefaultCredentials; 
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream receiveStream = response.GetResponseStream(); 
    StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); 
    string result = readStream.ReadToEnd(); 
    response.Close(); 
    readStream.Close(); 
    return result; 
}

修改之后,错误就消失了,程序也能正常发起请求拿到返回内容了。

内容的提问来源于stack exchange,提问作者cir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:52:51