简体   繁体   English

C#,WebRequest.Create(String URI)返回null

[英]C#, WebRequest.Create(String URI) returns null

I am trying to create a WebRequest to fetch data. 我正在尝试创建一个WebRequest来获取数据。 However, things aren't working out because for some reason I cannot create requests because WebRequest.Create() returns a null object. 但是,由于某些原因我无法创建请求,因为WebRequest.Create()返回空对象,所以事情没有解决。

My code is as follows: 我的代码如下:

WebRequest.RegisterPrefix("http://", WebRequestCreator.BrowserHttp);
WebRequest test = WebRequest.Create("http://www.google.com");

When I step through, after the second line, test is always null - no exceptions thrown. 当我逐步执行时,在第二行之后,测试始终为空-不引发任何异常。

I have no idea why a null object is returned. 我不知道为什么返回空对象。 What are possible reasons for this behaviour? 这种行为的可能原因是什么?

My feeling is that the first line is not necessary. 我的感觉是第一行不是必需的。 Try with 试试看

WebRequest test = WebRequest.Create("http://www.google.com");
 you can use following instead...

WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;// GetEncoding(1252);
UrlContent =client.DownloadString(url);

I don't recall such issue while using Silverlight (or developing Moonlight ;-). 我在使用Silverlight(或开发Moonlight ;-)时不记得这样的问题。 Maybe something else was already registered ? 也许其他东西已经被注册了?

Anyway you should be able to use: 无论如何,您应该可以使用:

WebRequestCreator.BrowserHttp.Create (new Uri ("http://www.google.com"));

to get the same result, ie ensuring a WebRequest instance was created using the browser HTTP stack. 获得相同的结果,即确保使用浏览器 HTTP堆栈创建了WebRequest实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM