使用WebRequest注册自定义协议

时间:2013-06-21 06:35:34

标签: c# webrequest

我正在访问一个需要自定义协议的Web服务器,而不是URL中的http。我曾尝试注册我的协议,但没有太多关于如何使其工作的文档。 Web服务器提供标准的HTTP响应,但如果请求没有使用custom://而不是http://,则它将不起作用。我想直接使用WebRequest底层功能,因为这最终是HTTP,但是,我需要一种方法来使用我的自定义协议URL提交请求。我这样注册:

WebRequest.RegisterPrefix("custom", new CustomWebRequestCreator());

但是,当我去创建WebRequest时,它会在此代码之后返回我的自定义类:

Uri uri = new Uri("custom://192.168.0.122:94934/resource");
System.Net.WebRequest request = WebRequest.Create(uri);

调试器说请求实际上是我的自定义类,但后来我得到了这个例外:

System.NotImplementedException was unhandled
  HResult=-2147467263
  Message=This method is not implemented by this class.
  Source=System
  StackTrace:
       at System.Net.WebRequest.GetResponse()
...

当我尝试将我的URL传递给WebRequest.Create()而不注册前缀时,我得到了这个例外:

System.NotSupportedException was unhandled
  HResult=-2146233067
  Message=The URI prefix is not recognized.
  Source=System
  StackTrace:
       at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
       at System.Net.WebRequest.Create(Uri requestUri)
   ...

知道如何才能让它发挥作用吗?

1 个答案:

答案 0 :(得分:0)

似乎不可能,或者从头开始达到为WebRequest重新实现HTTP的复杂程度。

我建议您改为使用WebRequest [http://localhost/resource]创建一个TCP中继,以便在不尝试扭曲WebRequest的情况下使其工作。继电器将转发到TCP套接字192.168.0.122:94934。

使用中继,您可以使用通用和简化的WebRequest对象。如果它适用于控制台/ webforms应用程序,则可以在应用程序启动时在另一个线程上启动(或者可以异步启动)。