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

如何在Delphi独立SOAP Web服务器中读取请求头信息

在Delphi SOAP服务端读取请求头信息的方法

基于VCL原生SOAP组件(THTTPSoapDispatcher + TWebModule)

如果你的SOAP服务器是用THTTPSoapDispatcher搭配TWebModule搭建的,直接通过TWebRequest对象就能读取请求头:

读取自定义请求头

假设前端在请求头里添加了X-Username和X-Password字段,代码示例:

procedure TWebModule1.WebModule1SOAPAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  Username, Password: string;
begin
  // 读取自定义请求头字段
  Username := Request.GetFieldByName('X-Username');
  Password := Request.GetFieldByName('X-Password');

  // 示例:验证用户名密码
  if (Username <> 'admin') or (Password <> '123456') then
  begin
    Response.StatusCode := 401;
    Response.Content := 'Unauthorized access';
    Handled := True;
    Exit;
  end;

  // 验证通过,继续处理SOAP请求
end;

处理标准Basic Auth请求头

如果前端用的是HTTP标准Basic认证(请求头格式为Authorization: Basic [base64编码的用户名+":"+密码]),可以解码获取账号密码:

uses IdCoderMIME, SysUtils;

procedure TWebModule1.WebModule1SOAPAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  AuthHeader, DecodedContent: string;
  ColonPos: Integer;
  Username, Password: string;
begin
  AuthHeader := Request.Authorization;
  if AuthHeader = '' then Exit;

  // 提取并解码Basic认证内容
  if StartsText('Basic ', AuthHeader) then
  begin
    DecodedContent := TIdDecoderMIME.DecodeString(Copy(AuthHeader, 7, MaxInt));
    ColonPos := Pos(':', DecodedContent);
    if ColonPos > 0 then
    begin
      Username := Copy(DecodedContent, 1, ColonPos - 1);
      Password := Copy(DecodedContent, ColonPos + 1, MaxInt);
      // 后续验证逻辑
    end;
  end;
end;

基于Indy的SOAP服务器

如果你的服务器是用TIdHTTPWebBrokerBridge搭建的,读取请求头的方式和上面完全一致,TWebRequest对象同样能访问所有请求头字段。

注意事项

  • 请求头名称大小写不敏感,但建议和前端保持统一命名风格,避免匹配失败
  • 若前端是跨域请求,需要在服务端响应头中添加Access-Control-Allow-Headers,明确允许自定义头(比如X-Username,X-Password),否则浏览器会拦截请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:22:42