1

知道如何使用 SoapCore 为我的呼叫添加标题吗?

到目前为止我所拥有的:

在startup.cs:
app.UseSoapEndpoint<IMyService>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer);

在 IMyService 中

[ServiceContract]
    public interface IMyService
    {      

        [OperationContract]
        public List<SOADataGetService> GetService(string ServiceType, string ServiceName, string ServiceVersion);
        
    }

然后我的肥皂就变成了这样:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:GetService>
         <tem:ServiceType>?</tem:ServiceType>
         <tem:ServiceName>?</tem:ServiceName>
         <tem:ServiceVersion>?</tem:ServiceVersion>
      </tem:GetService>
   </soapenv:Body>
</soapenv:Envelope>

我需要输入 <soapenv:Header/>用户名和密码

4

2 回答 2

0

您可以通过实现和注册文档IServiceOperationTuner中描述的自定义来访问 SoapCore 中的标头。

例如

public class MyServiceOperationTuner : IServiceOperationTuner
{
    public void Tune(HttpContext httpContext, object serviceInstance, SoapCore.ServiceModel.OperationDescription operation)
    {
        if (operation.Name.Equals(nameof(MyService.SomeOperationName)))
        {
            MyService service = serviceInstance as MyService;
            service.SetHttpRequest(httpContext.Request);
        }
    }
}
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.TryAddSingleton<IMyService, MyService>();
        services.TryAddSingleton<IServiceOperationTuner>(provider => new MyServiceOperationTuner());
    }
}
public class MyService : IMyService
{
    private ThreadLocal<HttpRequest> _httpRequest = new ThreadLocal<HttpRequest>() { Value = null };

    public void SetHttpRequest(HttpRequest request)
    {
        _httpRequest.Value = request;
    }

    public string SomeOperationName()
    {
        var soapHeader = GetHeaderFromRequest(_httpRequest.Value)
        return $"SOAP Header: {soapHeader}";
    }

    private XmlNode GetHeaderFromRequest(HttpRequest request)
    {
        var bytes = (request.Body as MemoryStream)?.ToArray();
        if (bytes == null)
        {
            // Body missing from request
            return null;
        }

        var envelope = new XmlDocument();
        envelope.LoadXml(Encoding.UTF8.GetString(bytes));

        return envelope.DocumentElement?.ChildNodes.Cast<XmlNode>().FirstOrDefault(n => n.LocalName == "Header");
    }
}
于 2021-06-07T11:15:02.057 回答
-2

不要使用过时的 SoapCore,尝试使用 SmartSoap: https ://github.com/Raffa50/SmartSoap

它也可以作为 nugetPackage 使用: https ://www.nuget.org/packages/Aldrigos.SmartSoap.AspNet/

看一看,试试看,如果您需要进一步的支持,我很乐意为您提供帮助!

于 2021-03-02T10:03:56.353 回答