c# – System.Net.WebClient在UploadString期间没有抛出错误到无效的url?

鉴于此代码,我预计会发生异常,但
System.Net.WebClient.UploadString会将空字符串返回到结果中.

我显然忽略了什么,但是什么?

using System.Net;
using System.Text;

[TestClass()]
public class WebClientTests
{
    [TestMethod()]
    public void WebClientUploadStringToInvalidUrlTest()
    {
        var webClient = new WebClient { Encoding = Encoding.UTF8 };
        var result =  webClient.UploadString("{{foo-bar}}", "snafu");
        Assert.IsTrue(string.IsNullOrEmpty(result));
    }

    [TestMethod()]
    [ExpectedException(typeof(ArgumentNullException))]
    public void WebClientUploadStringToNullUrlTest()
    {
        var webClient = new WebClient { Encoding = Encoding.UTF8 };
        string url = null;
        var result = webClient.UploadString(url, "snafu");
        Assert.IsTrue(string.IsNullOrEmpty(result));
    }

}

编辑:0700 by hanno也添加了一个null测试,这会抛出一个我想要的ArgumentNullException.

最佳答案 只有通过查看内部实现细节才能回答这个问题.

在准备中,WebClient类尝试从您在该重载中提供的字符串到UploadString构建一个真正的Uri.

代码在4.0框架中大致如下所示:

 if (!Uri.TryCreate(path, UriKind.Absolute, out address))
 {
      return new Uri(Path.GetFullPath(path));
 } 

TryCreate返回false为您的非URI符合路径,因此它回退到为您的字符串的Path.GetFullPath创建一个Uri,它返回一个带有file:// scheme的Uri.

在内部,WebClient使用WebRequest.Create获取能够处理给定schemeWebRequest.在您的情况下,将返回FileWebRequest(由于该方案为file://)

剥离所有检查和内部管道,在获得Uri后执行以下简化的调用序列:

        var fwr = (FileWebRequest) WebRequest.Create(new Uri(Path.GetFullPath(path)));
        fwr.Method ="POST";
        var us = fwr.GetRequestStream();
        var upload = Encoding.UTF8.GetBytes("snafu");
        us.Write(upload,0,upload.Length);
        us.Close();
        var sr = new StreamReader(fwr.GetResponse().GetResponseStream());
        return sr.ReadToEnd();

哪个不会抛出异常并返回一个空字符串.

你的假设“我希望这会引发异常”是错误的.

点赞