You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Delphi MARS REST API端点资源函数中获取客户端User-Agent

在Delphi MARS REST Library中获取客户端User-Agent的实现方法

完全可以在资源函数中获取客户端的User-Agent字符串,MARS REST Library提供了直接访问请求上下文的机制,能轻松读取HTTP请求头信息。

实现步骤与代码修改

  1. 引入必要单元:需要添加MARS.Core.Message和MARS.Core.Http单元,用于访问请求上下文和HTTP头。
  2. 注入请求上下文:在资源类中添加一个用[Context]注解标记的属性,MARS会自动将当前请求的上下文注入到该属性中。

修改后的完整代码如下:

type
  [Path('helloworld')]
  THelloWorldResource = class
  private
    [Context]
    FRequestContext: TMARSRequestContext; // 注入当前请求上下文
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

implementation

uses
  MARS.Core.Registry, MARS.Core.Message, MARS.Core.Http;

{ THelloWorldResource }

function THelloWorldResource.SayHelloWorld: string;
var
  UserAgent: string;
begin
  // 从请求头中读取User-Agent
  UserAgent := FRequestContext.Request.Headers['User-Agent'];
  
  // 处理客户端未发送User-Agent的情况
  if UserAgent.IsEmpty then
    UserAgent := 'Unknown Client';
    
  Result := 'Hello World! Your User-Agent: ' + UserAgent;
end;

补充说明

  • 无需客户端额外传递:User-Agent是HTTP请求的标准头字段,服务器端直接从请求上下文读取,不需要客户端通过请求体或自定义头传递。
  • 空值处理:如果客户端刻意篡改或不发送User-Agent,读取结果会是空字符串,需要提前做默认值处理。
  • 统计用途:你可以将获取到的User-Agent写入日志或存储到数据库,后续通过统计工具分析不同设备、浏览器的访问占比。

内容的提问来源于stack exchange,提问作者Shaun Roselt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:00:04