C#异步可插入协议包装默认HTTP协议抛出InvalidCastException

时间:2013-05-08 15:18:31

标签: c# .net internet-explorer http com

为了能够使用C#Web浏览器(WinForms)过滤获取的URL(包括JS,图像等),唯一可包含的选项似乎是包装HTTP的异步可插入协议(以及稍后的其他选项) )。不幸的是,在原来的原始协议实现几次调用之后抛出了InvalidCastException失败了 - 这也是奇怪的部分,它似乎在失败之前成功了好几次。

现在有些代码:

首先,协议的工厂已注册并附上:

  var ep = new FilteredHttpProtocolFactory();
  Guid id = Guid.Parse ("E00957BD-D0E1-4eb9-A025-7743FDC8B27B");
  session.RegisterNameSpace (ep, ref id, "http", 0, null, 0);

(工厂:)

[Guid ("EF474615-8079-4CFA-B114-6D1D28634DD8")]
[ComVisible (true)]
[ClassInterface (ClassInterfaceType.None)]
public class FilteredHttpProtocolFactory : IClassFactory
{
  public void CreateInstance (object pUnkOuter, Guid riid, out object ppvObject)
  {
    ppvObject = new FilteredHttpProtocol();
  }

  public void LockServer (bool fLock)
  {
  }
}

这是IE使用的原始HTTP协议,当使用它而不是包装器时,它可以正常工作:

[ComImport]
[Guid ("79eac9e2-baf9-11ce-8c82-00aa004ba90b")]
public class OriginalHttpHandler
{
}

这是包装器本身:

[Guid ("E00957BD-D0E1-4eb9-A025-7743FDC8B27B")]
[ComVisible (true)]
[ClassInterface (ClassInterfaceType.None)]
[AsyncProtocol (Name = "http2", Description = "blah")]
public class FilteredHttpProtocol : IInternetProtocol, IInternetProtocolRoot
{ 
private readonly IInternetProtocol _wrapped;

public FilteredHttpProtocol ()
{
  var originalHttpHandler = new OriginalHttpHandler();
  _wrapped = (IInternetProtocol) originalHttpHandler;
}

public void Start (string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
{
  _wrapped.Start (szURL, Sink, pOIBindInfo, grfPI, dwReserved);
}

public void Continue (ref _tagPROTOCOLDATA pProtocolData)
{
  _wrapped.Continue (ref pProtocolData);      // <- FAILS HERE
}
   // .... other methods from IInternetProtocol
    public uint Read (IntPtr pv, uint cb, out uint pcbRead)
    {
      return _wrapped.Read (pv, cb, out pcbRead); // <- OR HERE
    }
}

所以,奇怪的是,调用构造函数,Start()被调用,甚至Read()Continue()被调用几次,直到整个事情失败(使用{{ 1}}或Read())页面的某些部分已经可见(!),但似乎大多数缺少一个特定的图像(主要是!):

Continue()

看到我已经多次将对象强制转换为所述接口(这应该每次都会导致Unable to cast COM object of type 'Clients.Windows.Protocol.OriginalHttpHandler' to interface type 'Clients.Windows.Protocol.IInternetProtocol'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{79EAC9E4-BAF9-11CE-8C82-00AA004BA90B}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 E_NOINTERFACE)). 调用,并且在失败此错误之前已经多次调用(通过断点等验证)真是令人费解。通过查看引用计数,我已经排除了过早处置的对象(无论如何都没有意义)。

我尝试了几件事:

基本上我想要实现的是包装IE的默认http协议实现来过滤掉URL,包括从中检索资源的URL。我也会对合适的替代方案感到满意,但是他们必须符合GPLv2,可以与浏览器应用程序一起部署,并且不对系统的其余部分进行任何更改(即没有代理)。

感谢您的帮助;)

顺便说一下,这将成为我硕士论文的一部分:http://desktopgap.codeplex.com

2 个答案:

答案 0 :(得分:0)

目前我正在调查相同的行为。

我有两个想法。首先是从另一个创建它的线程调用该对象:

Method, Apartment, ThreadId, ObjId
--------------------
Constructor: , STA, 9, #1
Start: , STA, 9, #1
Continue: , STA, 9, #1
Read: , STA, 9, #1
Read: , STA, 9, #1
Lock: , STA, 9, #1
Read: , STA, 9, #1
Read: , STA, 9, #1
Constructor: , STA, 10, #2
Start: , STA, 10, #2
Constructor: , STA, 10, #3   <-- Notice ThreadId is 10
Terminate: , STA, 9, #1
Start: , STA, 10, #3         <-- Valid call
Constructor: , STA, 10, #4
Start: , STA, 10, #4
Read: , STA, 10, #4
Continue: , MTA, 11, #2
Terminate: , STA, 10, #4
Continue: , MTA, 12, #3      <-- EXCEPTION HERE!!! We have new thread with Id of 12 and MTA apartment
Constructor: , STA, 10, #5
Start: , STA, 10, #5
Constructor: , STA, 10, #6
Unlock: , STA, 9, #1
Start: , STA, 10, #6

其次认为CLR处理COM调用的方式与本机c ++不同。我试图利用DirectShow时遇到过这种情况。所以在c ++的情况下,它只需要指向接口并通过v-table调用函数。但是在托管代码的情况下,它首先查询接口。如果没有正确实现,那么额外的查询接口调用可能会失败或返回错误的对象。解决方案是创建本机IUknown包装器,它将在QueryInterface上返回指向IInternetProtocol的指针。

答案 1 :(得分:0)

经过一天的COM实验并在互联网上阅读各种各样的东西后,我找到了解决方案。

由于Simon Mourier指出这是一个线程问题:我创建的FilteredHttpProtocol支持STA和MTA与COM(= C#默认行为),默认的Http协议对象没有,并且在调用时来自不同线程的方法(显然发生了),Marshaling失败(也指出here)抛出E_NOINTERFACE。

由于改变COM线程行为显然有点奇怪(它需要写入注册表)并且对我不起作用,解决方案是在类工厂中创建自定义STA线程(即相同的线程)传递到每个FilteredHttpProtocol对象)(而不是Protocol类本身)并使用Invoke()调用每个方法。

快速而肮脏的解决方案是:

[ComVisible (true)]
public class FilteredHttpProtocolFactory : IClassFactory
{
    private readonly Control _ctrl;

    public FilteredHttpProtocolFactory ()
    {
      _ctrl = new Control();
    }

    public void CreateInstance (object pUnkOuter, Guid riid, out object ppvObject)
    {
      ppvObject = new FilteredHttpProtocol(_ctrl);
    }

    public void LockServer (bool fLock)
    {
    }
}

协议类本身:

[ComVisible (true)]
[AsyncProtocol (Name = "http2", Description = "blah")]
public class FilteredHttpProtocol :  IInternetProtocol, IInternetProtocolRoot
{
    private IInternetProtocol _wrapped;
    private static int s_id = 0;
    private int _id = -1;
    private int _creatingTID = -1;

    private Control _dispatcher;

    public FilteredHttpProtocol (Control ctrl)
    {
      _dispatcher = ctrl;
      _id = s_id;
      s_id++;
      _creatingTID = Thread.CurrentThread.ManagedThreadId;
      Debug.WriteLine ("#" + _id + " threadID: " + _creatingTID + " C'tor()");

      _dispatcher.Dispatcher.Invoke (
          () =>
          {
            var originalHttpHandler = new OriginalHttpHandler();
            _wrapped = (IInternetProtocol) originalHttpHandler;
          });
    }

    public void Start (string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
    {
      Debug.WriteLine ("#" + _id + " URL: " + "\t" + szURL);
      _dispatcher.Dispatcher.Invoke (
          () =>
          {
            Debug.WriteLine (
                "#" + _id + " original thread: " + _creatingTID + " calling thread " + Thread.CurrentThread.ManagedThreadId
                + " Start() "
                + Thread.CurrentThread.GetApartmentState());
            _wrapped.Start (szURL, Sink, pOIBindInfo, grfPI, dwReserved);
          });
    }

    public void Continue (ref _tagPROTOCOLDATA pProtocolData)
    {
      var _pProtocolData = pProtocolData;
      _dispatcher.Dispatcher.Invoke (
          () =>
          {
            Debug.WriteLine (
                "#" + _id + " original thread: " + _creatingTID + " calling thread " + Thread.CurrentThread.ManagedThreadId + " Continue() "
                + Thread.CurrentThread.GetApartmentState());
            _wrapped.Continue (ref _pProtocolData);
          });
      pProtocolData = _pProtocolData;
    }
    // ...
}

(请不要使用此代码;)) 感谢您的帮助,我希望这也有助于其他人。

干杯,

克劳斯