我试图通过在我的 C# 控制台应用程序中添加对服务的引用来调用服务。它需要承载身份验证。
当我从邮递员发帖时,它工作正常并返回响应。但是当我从 C# 代码访问它时,它返回 http 401 错误。
Postman CURL 看起来像这样:
curl --location 'https://api-secure-uat.com/v1' \
--header 'Content-Type: text/xml' \
--header 'SOAPAction: http://secure.com/Services/v1/CreateSession' \
--header 'Authorization: Bearer qv5bBU9HuQ0F5p3CT5EXAXbXd3w2' \
--data '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<CreateSession xmlns="http://secure.com/Services/v1/">
<reqCreateSession>
<client>
<name>hrix03hQoSwweIE1NuHrDHu5Ooz66jmx</name>
<clientId>hrix03hQoSwweIE1NuHrDHu5Ooz66jmx</clientId>
<appservername>test-client</appservername>
<appserverip>10.10.10.10</appserverip>
<appservertimestamp>2023-12-26T16:28:59.704Z</appservertimestamp>
<SubClientId xsi:nil="true"/>
<SubClientName xsi:nil="true"/>
<SalesAgentId xsi:nil="true"/>
<SalesAgentName xsi:nil="true"/>
</client>
</CreateSession>
</soap:Body>
</soap:Envelope>'
我正在尝试使用此 C# 代码来调用服务方法:
BasicHttpBinding binding = new BasicHttpBinding
{
Security = new BasicHttpSecurity
{
Mode = BasicHttpSecurityMode.Transport
}
};
// Create an instance of the service client
CoAServicesClient optixServiceclient = new CoAServicesClient(binding, new EndpointAddress(url));
// Add Bearer token to the HTTP request headers
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
requestProperty.Headers["Authorization"] = $"Bearer {bearerToken}";
OperationContextScope contextScope = new OperationContextScope(optixServiceclient.InnerChannel);
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
try
{
// Calling service method here
CreateSessionResponse csResponse = optixServiceclient.CreateSessionAsync(GetCreateSessionObject()).Result;
// Process the result here
Console.WriteLine($"Service response: {csResponse}");
}
catch (Exception ex)
{
Console.WriteLine($"Error calling service: {ex.Message}");
}
我可以看到我传递了正确的标头,但仍然收到 401。
任何人都可以指导代码不工作可能出现什么问题吗?
最好的部分是,即使 SOAPUI 也会抛出相同的错误 401,而只有邮递员似乎在工作。我能得到任何可能出问题的线索吗?
尝试代码:
CoAServicesClient optixServiceclient=new CoAServicesClient();
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers["Authorization"] = $"Bearer {bearerToken}";
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
一般来说,您不需要编写具有服务引用的端点和绑定。
CoAServicesClient optixServiceclient=new CoAServicesClient();
如果webservice中有其他设置,需单独说明。
调用服务时,请使用:
CreateSessionResponse csResponse =
optixServiceclient.CreateSessionAsync(GetCreateSessionObject()).Result;
但是,这种方法一般是WCF使用的。我想你也可以尝试httpclient。