TStream与Datasnap Rest和Close-session

时间:2017-07-07 08:26:13

标签: rest delphi session datasnap

我构建了一个datasnap REST应用程序,但我无法关闭会话。

例如,如果我在网络浏览器中调用我的网址4次: http://127.0.0.1:4445/REST/image?json=false

有4个会议开幕。

这是我的功能:

function TV1.TestImage:TStream;
var
ContentType : String;
FileStream : TFileStream;
begin
    FileStream := TFileStream.Create('C:\santiago.jpg', fmOpenRead or fmShareDenyNone);
    ContentType := 'image/jpg';

    GetInvocationMetadata.ResponseContentType := ContentType;
    ContentTypeHeaderToUse := ContentType;
    GetInvocationMetadata().ResponseCode := 200;

    result := FileStream;

    //Can't call CloseSession with TStream, pointer exception
    //GetInvocationMetaData.CloseSession := True;

end;

我使用WebModuleAfterDispatch就像那样:

  procedure TWebModule2.WebModuleAfterDispatch(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
  var session : TDSSession;
  begin
      response.FreeContentStream := true;

      if ContentTypeHeaderToUse<>'' then begin
          Response.ContentType := ContentTypeHeaderToUse;
          ContentTypeHeaderToUse := ''; // Reset global variable
      end;

  end;

如您所见,GetInvocationMetaData.CloseSession := True;无法在此处使用。

你知道如何在发送TStream后关闭会话吗?

1 个答案:

答案 0 :(得分:0)

在REST服务器上,我更喜欢返回base64字符串,它比客户端应用程序更容易处理,而不是Delphi TStream的JSON表示(字节数组)。

Soap.EncdDecd单元上的EncodeBase64函数非常容易进行转换:

function TV1.TestImage:string;
var MemoryStream: TMemoryStream;
begin
  MemoryStream := TMemoryStream.Create;
  MemoryStream.LoadFromFile('C:\santiago.jpg');
  Result := EncodeBase64(MemoryStream.Memory, MemoryStream.Size);
  MemoryStream.Free; // Now you can free the Stream yourself
end;

另一个好处是,您现在可以释放您的Stream而不依赖于Datasnap这样做。因此,您应该能够在没有指针异常的情况下手动关闭连接,并解决多个会话保持打开的问题。

您可以直接在Web应用程序上使用该base64图像字符串。您只需要在&lt;的开头添加它们的类型。 img&gt;标签

示例:

<img src="data:image/jpeg;base64,iV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