我在c#中使用WS并使用JavaScript进行调用。
我的服务遇到CrossDomain问题,我用jsonp
解决了。
但之后,我需要将json
更改为xml
,因为我在WS上使用soap标头进行身份验证(我不知道如何使用json调用json的头文件)。 / p>
当我更改为xml时,我发现了第3个问题:
我发送了带有cors标头的请求,但即使我使用的WS允许web.config
的起源,也不起作用。
<add name="Access-Control-Allow-Origin" value="*" />
如何配置我的WS以接收任何来源?
PS:我没有global.asax,因为我的项目不是一个网站,它是一个带有asmx的c#项目。
我的标题
public class MyHeader : SoapHeader
{
public int Authuser;
public string hash;
public bool Auntenticou()
{
//Validation
}
}
我的WS
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class Classe: System.Web.Services.WebService
{
public MyHeader head{ get; set; }
[SoapHeader("head")]
[WebMethod(Description = "methods.")]
public string Method()
{
if (head.Auntenticou())
{
//do something
return "Work";
}
else
{
return "Error";
}
}
调用 XML 和 JSON
function callXML(){
var url = "http://localhost/service.asmx/Method";
var soapXML =
"<?xml version='1.0' encoding='utf-8?'>" +
"<soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:tem='http://tempuri.org/'>"+
"<soap:Header>"+
"<tem:MyHeader>"+
"<tem:Authuser>1</tem:Authuser>"+
"<tem:hash>12345</tem:hash>"+
"</tem:MyHeader>"+
"</soap:Header>"+
"<soap:Body>"+
"<tem:Method>"+
// Parameters
"</tem:Method>"+
"</soap:Body>"+
"</soap:Envelope>";
$.ajax({
url: url,
type: "POST",
contentType: 'text/xml; charset=utf-8',
beforeSend: function(xhr) { xhr.setRequestHeader('SOAPAction', 'service.asmx/Method'); },
dataType: 'xml',
data: soapXML,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization"
},
success: function (data) {
console.log(data);
},
error: function (err) {
}
});
}
致电 jsonp (但我不知道如何将标头值“Authuser”和“hash”)
function jsonCall(){
var url = "http://localhost/service.asmx/Method";
$.ajax({
type: "POST",
url: url,
//contentType: "text/xml",
contentType: 'text/xml; charset=utf-8',
dataType: "jsonp",
crossDomain: true,
//headers: { "SoapHeader": soapXML },
data: { //jsonvalues
},
success: OnSuccessCall,
error: OnErrorCall
});
function OnSuccessCall(response) {
alert(response.d);
}
function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
}