Hello,
I created a webservice, and I am protecting access to the methods by using a soap header like this one:
public class MyWebService : System.Web.Services.WebService
{
// ....
public UserDetails userDetails;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[SoapHeader("userDetails")]
public string GetItemById(int Id)
{
if (userDetails != null && userDetails.IsValid())
{
Item item = getItem();
return new JavaScriptSerializer().Serialize(item);
}
else throw new Exception("Authentication failed");
}
//...
}
public class UserDetails : System.Web.Services.Protocols.SoapHeader
{
public string userName { get; set; }
public string password { get; set; }
public bool IsValid()
{
return this.userName == "name" && this.password == "1234";
}
}Now I want to call that webservice from Jquery. from the unprotected methods it works all right, but in that protected method there is something wrong: the header is always null, therefore the authentication fails always.
I think I must be doing something wrong in the way I send the data to the webservice when I do the JQuery call. I put this code together after reading varios post in internet about how to send headers to a webservice, but obviously I am missing something:
$("#Test").click(function () {
var soapXML =
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +" <soap:Header>" +"<UserDetails xmlns='http://tempuri.org/'>" +"<Username>test</Username>" +"<Password>1234</Password>" +"</UserDetails>" +"</soap:Header>" +"<soap:Body>" +"<GetItemById xmlns='http://tempuri.org/' />" +"</soap:Body>" +"</soap:Envelope>";$.ajax({
url: "http://localhost:2232/MyWebService.asmx/GetItemById",
type: "POST",
dataType: "xml",
contentType: "text/xml; charset=utf-8",
data: soapXML,
beforeSend: function (xhr) {
xhr.setRequestHeader('SOAPAction', 'http://localhost:2232/MyWebService/GetItemById');
},
success: function (data) {
console.log(data);
},
error: function (err) {
console.log(err);
}
});
});Could anybody indicate me how to properly send the data to the webservice?
Also, all the examples I found in the internet tell me to create that XML string to send the headers data. When I do not use the authentication I can send the data to the server like this:
data:"{Id:123}"Which is way easier to read than the XML. I have also prepared the service to return data in the JSON format. There is a way to send that Soap headers data, in the same way as the parameters of the function (as a JSON)?
Thanks for your help.