我有这个错误 System.ServiceModel.Security.MessageSecurityException

I have this error System.ServiceModel.Security.MessageSecurityException

根据我的阅读和理解,当我没有发送身份验证时会发生这种情况。

但是我尝试了两种方式发送:

string userN = "username";
string _pasw = "password";
BasicHttpBinding binding = new BasicHttpBinding();
Endpoint wsdl = new Endpoint("MyEndpoint");


SoapClient client = new SoapClient(binding, wsdl);
client.ClientCredentials.UserName.UserName = userN;
client.ClientCredentials.UserName.Password = _pasw;
await client.OpenAsync();

并且:

HttpClient request = new HttpClient();
var svcCredentianls = Encoding.ASCII.GetBytes(userN + ":" + _pasw);
request.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(svcCredentianls));

但是我遇到了这样或那样的错误:

System.ServiceModel.Security.MessageSecurityException: 'The HTTP request is not authorized with the "Anonymous" client authentication scheme. The authentication header received from the server was "Basic realm="SAP NetWeaver Application Server [PRD/400]"".'

我错在哪里或遗漏了什么?

我认为问题出在您 web.config 中的绑定配置。 请检查安全节点。

<security mode="Transport">
  <transport clientCredentialType="Basic" proxyCredentialType="Basic" realm="" />
</security>

您可以在下面找到我的工作示例:

<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                useDefaultWebProxy="true">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <security mode="Transport">
                    <transport clientCredentialType="Basic" proxyCredentialType="Basic" realm="" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address="https://pc:8080/Service.svc/SslService" binding="basicHttpBinding"
            bindingConfiguration="BasicHttpBinding_IService" contract="ServiceReference1.IService"
            name="BasicHttpBinding_IService" />
    </client>
</system.serviceModel>

如果您不使用 web.config 配置,您可以尝试调整 BasicHttpBinding 创建代码:

BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;