2007. január 14., vasárnap

How to really do before and after processing on web requests using borlands web module


Problem/Question/Abstract:

Do you not know where to put CoInitialize or CoUnitialize?

The problem with Borlands web module architech is that there is no true after dispatch method.  Yes, there is one but it only gets called only if your response was handled by an action item and will not get called if your response was sent by an action item.  I have a complete and simple solution for this problem that will allow you to execute code before an after handling a response.. always.

Answer:

First a code listing, then an explanation.

procedure TWebModule1.WebModuleBeforeDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  PrevBeforeDispatchMethod: THTTPMethodEvent;
begin
  Handled := True;
  {
    ******* Do initialization code here such as CoInitialize
  }
  try
    PrevBeforeDispatchMethod := BeforeDispatch;
    try
      BeforeDispatch := nil;
      {
        ****** Process anything before calling Action Items here
      }
      DispatchAction(Request, Response);
    finally
      BeforeDispatch := PrevBeforeDispatchMethod;
    end;
  finally
    {
      ******* Do cleanup here such as CoUnInitialize
    }
  end;
end;

Now, to explain.

You need to create an OnBeforeDispatch event, then paste the above code into it. This bypasses Borlands behavior in a way.

This is what goes on behind the scenes....

Borlands web application calls your web modules DispatchAction method, the dispatch action event then calls your BeforeDispatch event if you have assigned one... now for the trick, if your BeforeDispatch event handles the request then no action item will be called. I take advantage of that behavior.  The Dispatach event will be called 2 times, once by the web application and a second time by the above code... to prevent recursion I set the BeforeDispatch event to nil.  Because I set handled to true, the first call made by the web application will not call any action items... remember if the BeforeDispatch event Sets handled to true then the DispatchAction event will not call action items.  Therefore my BeforeDispatch event calls the action items through a second call to DispatchAction... DispatchAction will not call my BeforeDispatch event because I set it to nil before calling DispatchAction.

There is one problem that can occur, AfterDispatch will be called 2 times. If you are not using the AfterDispatch event then you have no problems.

I suggest you not use the AfterDispatch event handler or write some code to prevent your code executing 2 times.

Nincsenek megjegyzések:

Megjegyzés küldése