Does System.Net.WebClient not throw an error during UploadString on an invalid URL?

Given this code, I expected an exception to occur, but System.Net.WebClient.UploadString returns an empty string in result.

I'm obviously missing something, but what?

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

}

edit: how a test was added for a suggestion from hannonull , and it also throws a ArgumentNullException, which I expect.

+4
source share
1 answer

This can be answered by looking at the internal implementation details.

WebClient Uri , , UploadString.

4.0:

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

TryCreate false URI, Uri Path.GetFullPath , Uri file://scheme.

WebClient WebRequest.Create WebRequest, scheme. 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();

.

" , " .

+2

Source: https://habr.com/ru/post/1543565/


All Articles