Search code examples
delphiuser-agent

How do I get the User-Agent of the client from within an endpoint resource function in the Delphi MARS REST API Library?


I've built a basic API with the MARS REST Library in Delphi and I am wondering whether there is a way to get the User-Agent of the client connecting to the endpoint in some way from the resource function. What is the correct "MARS" way to do this?

As an example, I have the following code:

type
  [Path('helloworld')]
  THelloWorldResource = class
  protected
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

implementation

uses
  MARS.Core.Registry;

{ THelloWorldResource }

function THelloWorldResource.SayHelloWorld: string;
begin
  Result := 'Hello World!';
end;

How can I get the User-Agent String from within my SayHelloWorld function? Is this even possible?

I basically want to know where the request is coming from for each endpoint and also for statistics to see which user agent devices are most common on my requests. I need to get this from server side and not sent from client side through the endpoint body or headers, because anyone can modify the User-Agent from the client side or even simply not send any at all.


Solution

  • There's a GetUserAgent function within the IMARSRequest interface that you can use for this. The IMARSRequest interface is part of the MARS.Core.RequestAndResponse.Interfaces unit.

    Here's your code, but modified to get the User-Agent String using the above mentioned GetUserAgent function:

    type
      [Path('helloworld')]
      THelloWorldResource = class
      protected
        [Context] MarsRequest: IMARSRequest;
      public
        [GET, Produces(TMediaType.TEXT_PLAIN)]
        function SayHelloWorld: string;
      end;
    
    implementation
    
    uses
      MARS.Core.Registry;
    
    { THelloWorldResource }
    
    function THelloWorldResource.SayHelloWorld: string;
    begin
      var UserAgent := MarsRequest.GetUserAgent;
      Result := 'Hello, your User Agent String is: ' + sLineBreak + UserAgent;
    end;
    

    To show the code working. Here's a request I did from Postman:

    Postman User-Agent Request

    Hello, your User Agent String is:

    PostmanRuntime/7.32.3

    And then I did another request from my browser using JavaScript and this was the response there:

    Hello, your User Agent String is:

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82