C# WCF GetWebRequest:如何在 Headers 中设置属性

C# WCF GetWebRequest: how can I set an Attribute in the Headers

覆盖 GetWebRequest 并访问 Headers 工作得很好。现在我需要设置一个属性。我的目标看起来像

<soapenv:Envelope xmlns:urn="urn:company:sap:ds:sales" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
  <messageId xmlns="http://www.company.com/foo/bar/soap/features/messageId/">urn:uuid:123c155c-3ab4-19ca-a045-02003b1bb7f5</messageId>
</soapenv:Header>
<soapenv:Body>
    ...
</soapenv:Body>
</soapenv:Envelope>

问题是如何在Header中生成xmlns="http://www.company.com/foo/bar/soap/features/messageId"属性。我刚花了几个小时阅读文档,似乎根本无法在 header.

中设置属性

我可以简单地引用引号然后写

request.Headers["messageID xmlns=""http://www.company.com/foo/bar/soap/features/messageId"""] = "urn:uuid:123c155c-3ab4-19ca-a045-02003b1bb7f5";

但这对我来说有点不对劲..

请参考以下代码片段,希望对您有用。

    class Program
    {
        static void Main(string[] args)
        {
            ServiceReference1.ServiceClient client = new ServiceClient();
            using (new OperationContextScope(client.InnerChannel))
            {
                UserInfo userInfo = new UserInfo();
                userInfo.FirstName = "John";
                userInfo.LastName = "Doe";
                MessageHeader aMessageHeader = MessageHeader.CreateHeader("UserInfo", "http://tempuri.org", userInfo);
                MessageHeader bheader = MessageHeader.CreateHeader("messageId", "http://www.company.com/foo/bar/soap/features/messageId/", "urn:uuid:123c155c-3ab4-19ca-a045-02003b1bb7f5");
           OperationContext.Current.OutgoingMessageHeaders.Add(aMessageHeader);
                OperationContext.Current.OutgoingMessageHeaders.Add(bheader);
                var result = client.Test();
                Console.WriteLine(result);
            }
        }
    }
    public class UserInfo
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

结果。

这是client-side上的实现,你也可以使用IClientMessageInspectorIDispatchMessageInspector接口在client-side和server-side上添加自定义header .
如果有什么我可以帮忙的,请随时告诉我。