I am having an issue when calling an external third-part soap web service: the error am getting is 'The remote server returned an error: (500) Internal Server Error.'(from client), but the problem is when I do call using SoapUI 5.4.0 (on the same PC under the same user) it runs fine. The code works on any other web services.
Can someone give me any idea?
using System;
using System.IO;
using System.Net;
using System.Xml;
namespace ConsoleApp1
{
class Program
/// Soap WebService call
public static void Execute()
{
HttpWebRequest request = CreateWebRequest();
request.Credentials = CredentialCache.DefaultCredentials;
XmlDocument soapEnvelopeXml = new XmlDocument();
NewMethod(soapEnvelopeXml);
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
Console.WriteLine("Done!");
Console.ReadKey();
}
}
}
private static void NewMethod(XmlDocument soapEnvelopeXml)
{
soapEnvelopeXml.LoadXml(xml: #"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:out=""http://www.test.com/test/Services/Outage""><soap:Header/><soap:Body><out:GetLocations/></soap:Body></soap:Envelope>");
}
/// Create a soap webrequest to [Url]
public static HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://test:557/OutageService.svc");
webRequest.ContentType = #"application/soap+xml;charset=UTF-8";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
static void Main(string[] args)
{
Execute();
}
}
}
And SoapUI 5.4.0 (I've changed the domain name to 'test')
XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:out="http://www.test.com/test/Services/Outage">
<soap:Header/>
<soap:Body>
<out:GetLocations/>
</soap:Body>
</soap:Envelope>
RAW
POST http://test:557/OutageService.svc HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/soap+xml;charset=UTF-8;action="http://www.test.com/test/Services/Outage/IOutageService/GetLocations"
Content-Length: 390
Host: test:557
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Respond
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 155883
Content-Type: application/soap+xml; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 12 Mar 2018 16:09:46 GMT
<s:Envelope xmlns:s="http://www.w3.org/2003/05/so.........
SoapUI
Thank you #Broom!
I've done a few tests using fiddler and I've got the following message:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header>
<a:Action s:mustUnderstand="1">http://www.w3.org/2005/08/addressing/fault</a:Action></s:Header><s:Body><s:Fault><s:Code><s:Value>s:Sender
</s:Value><s:Subcode><s:Value>
a:ActionMismatch</s:Value></s:Subcode></s:Code><s:Reason><s:Text xml:lang="en-US">
The SOAP action specified on the message, '"http://www.test.com/test/Services/Outage/IOutageService/GetLocations"',
does not match the HTTP SOAP Action, 'http://www.test.com/test/Services/Outage/IOutageService/GetLocations'.
</s:Text></s:Reason><s:Detail><a:ProblemHeaderQName>a:Action</a:ProblemHeaderQName></s:Detail></s:Fault></s:Body></s:Envelope>
so in my code I've changed
private static void NewMethod(XmlDocument soapEnvelopeXml)
{
soapEnvelopeXml.LoadXml(xml: #"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:out=""http://www.test.com/test/Services/Outage""><soap:Header/><soap:Body><out:GetLocations/></soap:Body></soap:Envelope>");
}
to the following
soapEnvelopeXml.LoadXml(xml: #"<soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:out=""http://www.test.com/test/Services/Outage""><soap:Header xmlns:wsa=""http://www.w3.org/2005/08/addressing""><wsa:Action>http://www.test.com/test/Services/Outage/IOutageService/GetLocations</wsa:Action></soap:Header><soap:Body><out:GetLocations/></soap:Body></soap:Envelope>");
Which defines the Action in Content-Type
Content-Type: application/soap+xml;charset=UTF-8;action="http://www.test.com/test/Services/Outage/IOutageService/GetLocations"
And then I've changed Content-Type in WebRequest
var contentString = #"application/soap+xml;charset=UTF-8;action=""http://www.test/test/Services/Outage/IOutageService/GetLocations""";
webRequest.ContentType = contentString;
And the code receives the xml from web service.
Just need to be aware of double quotes!!!!
Related
My web service client is returning a ? for French characters. My client is calling an axis2/c web service on Apache. I usedwsdl.exe to generate a c# proxy class. When I look at the return in TCPMON, I can see the French characters correctly but in c# they are just showing up as ?. Here is my request and response captured from TCPMON session:
------Request ---
POST /axis2/services/Common HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.18444)
VsDebuggerCausalityData: uIDPo2iKyNQi9MNOvFI9y0jK6aYAAAAA1bUF2S4JzkGiYsQ0+oayv1AuqfqiggxBj2stf8zH7O4ACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: ""
Host: localhost:9559
Content-Length: 338
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><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><getCriteria xmlns="http://Common.media.jda.com/service"><userId>2285</userId></getCriteria> </soap:Body></soap:Envelope>
----Response ------------
HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Wed, 10 Jun 2015 20:36:41 GMT
Server: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/0.9.8e-fips-rhel5 Axis2C/1.6.0
Content-Length: 2052
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body><n:getCriteriaResponse xmlns:n="http://Common.media.jda.com/service"><n:getCriteriaReturn> <n:criteriaId>18219</n:criteriaId><n:criteriaDesc>1415 S PRIMETIMEá</n:criteriaDesc><n:userId>2285</n:userId> <n:seasonCode>1415</n:seasonCode><n:marketType>S</n:marketType><n:networkCode>P</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18972</n:criteriaId><n:criteriaDesc>1415 U Daytimeá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1415</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>M</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18221</n:criteriaId><n:criteriaDesc>1415 U PRIMETIMEá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1415</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>P</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn><n:getCriteriaReturn><n:criteriaId>18284</n:criteriaId><n:criteriaDesc>1516 DADT Upfrontá</n:criteriaDesc><n:userId>2285</n:userId><n:seasonCode>1516</n:seasonCode><n:marketType>U</n:marketType><n:networkCode>I</n:networkCode><n:networkDaypartId>0</n:networkDaypartId><n:salesTypeId>0</n:salesTypeId><n:advId>0</n:advId><n:agencyId>0</n:agencyId><n:acctExecId>0</n:acctExecId><n:plannerId>0</n:plannerId><n:defaultInd>false</n:defaultInd></n:getCriteriaReturn></n:getCriteriaResponse> </soapenv:Body></soapenv:Envelope>
Any help would be greatly appreciated. Here is my function in the proxy class generated by wsdl.exe:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", RequestNamespace="http://Common.media.jda.com/service", ResponseNamespace="http://Common.media.jda.com/service", Use=System.Web.Services.Description.SoapBindingUse.Default, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
[return: System.Xml.Serialization.XmlElementAttribute("getCriteriaReturn")]
public CriteriaRec[] getCriteria(int userId) {
object[] results = this.Invoke("getCriteria", new object[] {
userId});
return ((CriteriaRec[])(results[0]));
}
I was able to resolve this issue by creating and override function:
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse webResponse = base.GetWebResponse(request);
webResponse.Headers["Content-Type"] = "text/xml; charset=iso-8859-15";
return webResponse;
}
This works fine. In addition, I specified the requestEncoding to take care of sending data back:
myservice.RequestEncoding = System.Text.Encoding.GetEncoding("iso-8859-15");
I am trying to create a simple XML SOAP request to a web service.
The service itself is proven to be OK, I accessed it by using WSDL-generated class without any problems. But if I try to access it using regular WebRequest - it always returns 400 Bad Request.
Here's my code:
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = CreateWebRequest("http://localhost:8000/ExchangeService", "WhoAmI");
XmlDocument SoapEnvelopeXml = new XmlDocument();
SoapEnvelopeXml.LoadXml(
#"<?xml version=""1.0""?>
<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope""
xmlns:tem=""http://tempuri.org"">
<soapenv:Header/>
<soapenv:Body>
<tem:WhoAmI/></soapenv:Body></soapenv:Envelope>");
using (Stream stream = request.GetRequestStream())
{
SoapEnvelopeXml.Save(stream);
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
}
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
public static HttpWebRequest CreateWebRequest(string url, string soapAction)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=UTF-8;action=\"" + soapAction + "\"";
webRequest.Method = "POST";
return webRequest;
}
}
The XML is generated by SoapUI and works there perfectly. Here is the SoapUI's HTTP header:
POST http://localhost:8000/ExchangeService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://tempuri.org/IExchangeFunctions/WhoAmI"
Content-Length: 211
Host: localhost:8000
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
What am I doing wrong?
UPD: changed the service from my to some third-party:
http://wsf.cdyne.com/WeatherWS/Weather.asmx
Through WSDL - it works. SoapUI returns data. From my code - Internal Error 500.
Try remove carriage return from soap message
.Replace("\r\n", "");
If not work verify the http request sended with fiddler, to me it was very helpful.
I am trying to send Facebook graph link to the AppEngine server. I receive "Malformed string exception". Here is my method sending json to server:
public async Task<string> SendJSONData(string urlToCall, string JSONData)
{
// server to POST to
string url = urlToCall;
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
string json = "action=" + JSONData;
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
WebResponse response = await httpWebRequest.GetResponseAsync();
StreamReader requestReader = new StreamReader(response.GetResponseStream());
String webResponse = requestReader.ReadToEnd();
return webResponse; }
Here is what I sniff using Fiddler:
POST http://x.appspot.com/register HTTP/1.1
Accept: */*
Content-Length: 376
Accept-Encoding: identity
Content-Type: application/x-www-form-urlencoded
User-Agent: NativeHost
Host: x.appspot.com
Connection: Keep-Alive
Pragma: no-cache
action={
"mailFb": "mail#gmail.com",
"userName": "Michael",
"userSurname": "w00t",
"nickname": "Michael w00t",
"userSex": "male",
"userAvatar": "https://graph.facebook.com/myperfectid/picture?type=large&access_token=BlahblahblahblahToken"
}
So everything looks fine, but the problem is that i receive the following error in AppEngine log:
2013-03-02 17:52:10.431 /register 500 56ms 0kb NativeHost
W 2013-03-02 17:52:10.427 /register com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 column 79 at com.google.g
C 2013-03-02 17:52:10.429 Uncaught exception from servlet com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 colu
I managed to narrow the problem to its source, which is "&" character. So my question is, how to fix the code, so that it works with AppEngine.
Oh, here is how i read the received data on the server:
gson.fromJson(reader, User.class);
The problem is highlighted by the fact you're claiming you are sending "Content-Type: application/x-www-form-urlencoded"
But it isn't. Hence the error.
The correct encoding for & is &.
Has been using Service Reference without any success:
Web service return only XML
Now I am using the raw SOAP message to do it:
XmlDocument doc = new XmlDocument();
doc.Load("Service.xml");
// create the request to your URL
Uri wsHost = new Uri("http://www.rrr.net/services/Connect");
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(wsHost);
// add the headers
// the SOAPACtion determines what action the web service should use
request.Headers.Add("SOAPAction", "act");
// set the request type
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";
// add our body to the request
Stream stream = request.GetRequestStream();
doc.Save(stream);
stream.Close();
// get the response back
using( HttpWebResponse response = (HttpWebResponse)request.GetResponse() )
{
Stream dataStream = response.GetResponseStream();
StreamReader dataReader = new StreamReader(dataStream);
// Use Linq to read the xml response
using (XmlReader reader = XmlReader.Create(dataStream))
{
The post is correct, but response always give me text/plain empty result, the reponse header:
Headers = {Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain
Date: Thu, 06 Sep 2012 15:59:28 GMT
}
The SOAP message is, act is the function:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webService">
<soapenv:Header/>
<soapenv:Body>
<web:act>
<web:d1>1</web:d1>
<web:d2>14</web:d2>
</web:act>
</soapenv:Body>
</soapenv:Envelope>
I use SoapUI, below is the raw request from SoapUI, it return a xml result:
POST http://www.rrr.net/services/Connect HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: ""
Content-Length: 516
Host: www.rrr.net
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Thank you.
SOAP webservices require action/method to be specified (and NOT empty). If you don't know which action you want you can look at webservice WSDL by invoking the webservice with queryString "?WSDL". I.e. www.yourSite.com/your/Web/Service/URL?WSDL
You must specify an action in both the request and also the service interface. You can set the action value on the interface member using the attributes shown below and then in the request using the method you have used but by specifying the action name you used in the contract:
The attributes on the interface member
[OperationContract Name="YourActionName"]
[WebInvoke (Method = "POST", UriTemplate = "YourActionName")]
Message YourServiceFunction();
One method of specifying the action on the message
Message inputMessage = Message.CreateMessage (MessageVersion.Soap, "YourActionName", reader);
I write here because I'm working to transform a PHP webservice client to C# (VS2010).
Project are in Framework4 but the web service was added in VS2010 like a web service compatible with Framework2 (Web Reference with WSDL).
Actually I'm working only on a classical webservice (a Helloworld test).
With the client C# I have no problem I send a text to the web service and the web service responds by returing the text. I have no error in the Apache Server.
If I activate the basic authentification in the .htaccess apache server (host the webservice server), so in the client C# I have this error :
Exception : WebException
Bad Request with state HTTP 400 : Bad Request.
In Apache error log I see this line :
[Thu Feb 02 23:52:06 2012] [error] [client XX.XX.XX.XX] Invalid URI in request
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="https://www.domaine.com/api/helloworld/webservices.php?wsdl"
xmlns:types="https://www.domaine.com/api/helloworld/webservices.php?wsdl/encodedTypes"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org
/2001/XMLSchema">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:bonjour><prenom xsi:type="xsd:string">Toto</prenom></tns:bonjour>
</soap:Body>
</soap:Envelope>
POST /api/helloworld/webservices.php HTTP/1.1
.
I'm sure is the credentials who are not working because when I try with a false user and password I have always the 400 Bad Request.
The code of C# Client are :
// We create the webservice
WebService mywebservice = new WebService();
// We define BASIC Authentication
CredentialCache myCredentials = new CredentialCache();
NetworkCredential netCred = new NetworkCredential("User1", "Pass1");
myCredentials.Add(new Uri(mywebservice.Url), "Basic", netCred);
myCredentials.PreAuthenticate = true;
mywebservice.Credentials = myCredentials;
// We define the UserAgent
mywebservice.UserAgent = ".NET Framework";
// We call the function of webservice
string retour = mywebservice.bonjour("Tata");
// We show the return
MessageBox.Show(retour, "Retour de l'API", MessageBoxButtons.OK, MessageBoxIcon.Information);
.
The .htaccess :
# Don't show directory listings for URLs which map to a directory.
Options -Indexes
# Se logue avec un compte AD
AuthType Basic
AuthBasicProvider ldap
AuthName "Acces au webservice"
AuthLDAPURL ldap://127.0.0.1:389/ou=clients,dc=domaine,dc=com?mail
Require valid-user
.
If I delete the .htaccess file everything it's working ... but without authentication :(
I post also the request and response with .htaccess (not working) :
POST https://www.domaine.com/api/login_ovh_pnp/webservices.php HTTP/1.1
User-Agent: .NET Framework
VsDebuggerCausalityData: uIDPo9/Tb/xbJxtKvSNra7boyJsAAAAAQcQin1OhXXXXXXXXXXX/KqROJW0w1FhAcrrhI1sGQACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl#bonjour"
Authorization: Basic bHZlaXJtYW5AYXF1aWxhLWXXXXXXXXXXXbmcuZnI6ZHluYXRlcmE3OA==
Host: www.domaine.com
Content-Length: 623
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl"
xmlns:types="https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl
/encodedTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:bonjour>
<prenom xsi:type="xsd:string">Tata</prenom>
</tns:bonjour>
</soap:Body>
</soap:Envelope>
=====================================
=====================================
HTTP/1.1 400 Bad Request
Date: Mon, 06 Feb 2012 13:40:32 GMT
Server: Apache
Vary: Accept-Encoding
Content-Length: 226
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
</body></html>
.
And for finish the request without .htaccess :
POST https://www.domaine.com/api/login_ovh_pnp/webservices.php HTTP/1.1
User-Agent: .NET Framework
VsDebuggerCausalityData:
uIDPo4r/MO3TgmdMkQiWHfkXoWwAAAAA1krYOM0NBkS9vLzFQe3Vmln8F3GXClFNrTWXL/L622YACQAA
Content-Type: text/xml; charset=utf-8
SOAPAction: "https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl#bonjour"
Host: www.domaine.com
Content-Length: 623
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tns="https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl"
xmlns:types="https://www.domaine.com/api/login_ovh_pnp/webservices.php?wsdl
/encodedTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:bonjour>
<prenom xsi:type="xsd:string">Tata</prenom>
</tns:bonjour>
</soap:Body></soap:Envelope>
=====================================
=====================================
HTTP/1.1 200 OK
Date: Mon, 06 Feb 2012 13:51:31 GMT
Server: Apache
X-SOAP-Server: NuSOAP/0.9.5 (1.123)
Content-Length: 575
Vary: Accept-Encoding
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/xml; charset=ISO-8859-1
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:bonjourResponse xmlns:ns1="https://supervision.dynatera.net/api/login_ovh_pnp/webservices.php?wsdl">
<return xsi:type="xsd:string">Bonjour Tata</return></ns1:bonjourResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
.
Thank you very much for your help on this complex problem because I searched many times without found anything to fix this issue.
I've also had this problem...
When you define NetworkCredentials it does not get sent in the HTTP header, and thus no 'Authorization' header...
What I did and it worked for me was:
I created a class that implements IClientMessageInspector and implement the BeforeSendRequest method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
namespace BasicAuth
{
public sealed class MessageHttpHeaderInspector : IClientMessageInspector
{
private string userName;
private string password;
#region Constructor
public MessageHttpHeaderInspector(string userName, string password)
{
this.userName = userName;
this.password = password;
}
#endregion
#region IClientMessageInspector Members
public void AfterReceiveReply(ref Message reply, object correlationState)
{
//throw new NotImplementedException();
}
public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequest;
if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
}
else
{
httpRequest = new HttpRequestMessageProperty();
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequest);
}
if (httpRequest != null)
{
string credentials = this.CreateBasicAuthenticationCredentials(this.userName, this.password);
httpRequest.Headers.Add(System.Net.HttpRequestHeader.Authorization, credentials);
}
return request;
}
#endregion
#region Private Worker Methods
private string CreateBasicAuthenticationCredentials(string userName, string password)
{
string returnValue = string.Empty;
string base64UsernamePassword = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", userName, password)));
returnValue = String.Format("Basic {0}", base64UsernamePassword);
return returnValue;
}
#endregion
}
}
Then I created a class that implements IEndpointBehavior and implements the ApplyClientBehavior method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
namespace BasicAuth
{
public sealed class CustomEndpointCallBehavior : IEndpointBehavior
{
private string userName;
private string password;
#region Constructor
public CustomEndpointCallBehavior(string userName, string password)
{
this.userName = userName;
this.password = password;
}
#endregion
#region IEndpointBehavior Members
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
//throw new NotImplementedException();
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(new MessageHttpHeaderInspector(this.userName, this.password));
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
//throw new NotImplementedException();
}
public void Validate(ServiceEndpoint endpoint)
{
//throw new NotImplementedException();
}
#endregion
}
}
Then you need to apply this behavior to the proxy:
mywebservice.Endpoint.Behaviors.Add(new CustomEndpointCallBehavior("User1", "Pass1"));
Have a look at the following:
http://dkochnev.blogspot.com/2011/05/framework-40-wcf-basic-authentication.html
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iendpointbehavior.aspx
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iclientmessageinspector.aspx
This should do the trick...
Hope it works for you!
Credentials set in your code does not match credentials sent in request
Authorization: Basic bHZlaXJtYW5AYXF1aWxxxxxx1bHRpbmcuZnI6ZHluYXRlcmE3OA==
Your code set next credential for basic authentication:
// We define BASIC Authentication
CredentialCache myCredentials = new CredentialCache();
NetworkCredential netCred = new NetworkCredential("User1", "Pass1");
But credentials inside Authorization Request token are:
"lveirman#aquila-XXXXXXX.fr:dynXXXXXXX"
(I recommend you to edit your post and remove the base64 Authentication tokens, additionally is a good idea to change your network password ASAP << DONE)