5

我正在访问需要自定义协议而不是 url 中的 http 的 Web 服务器。我试图注册我的协议,但没有太多关于如何让它工作的文档。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)
   ...

知道如何让这个工作吗?

4

1 回答 1

0

It doesn't seem possible, or would be reaching the level of complexity of re-implementing HTTP for WebRequest from scratch.

I suggest you instead create a TCP relay, which you connect to using WebRequest [http://localhost/resource], in order to make it work without trying to contort WebRequest. The relay would in turn forward to TCP socket 192.168.0.122:94934.

With a relay, you use the common and simplified WebRequest object. If it's for a console/webforms applicaiton, the relay can be started on another thread (or can be started asynchronously), when the application is started.

于 2015-01-23T03:46:18.073 回答