我遇到跨域Ajax调用问题。当我通过Ajax Call调用asp.net WebMethod时,我收到警告:原因:CORS预检频道没有成功
这是完整的代码
服务器代码:
using System;
using Customers.BLL;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.Http.Cors;
[EnableCors(origins: "*", headers: "*", methods: "*")]
public partial class API_Default : System.Web.UI.Page
{
static string ApplicationPath = "";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ValidateUser(string UserName)
{
string strJson = "";
var User = Members.GetCustMaster(UserName);
if (User != null)
{
User.BankName = ApplicationPath + (User.BankName.ToString() != "" ? "Images/Photos/" + User.BankName : "images/avatar.png");
strJson = JsonConvert.SerializeObject(User);
}
else
{
JavaScriptSerializer json = new JavaScriptSerializer();
Failure failure = new Failure();
strJson = json.Serialize(failure);
}
return strJson;
}
}
[Serializable]
public class Failure
{
public bool Status { get { return false; } }
public string Result { get { return "Record Not found"; } }
}
我在Web.config中添加了Headers
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, X-Token" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
这是我试图调用这个webmethod的方式
<head>
<title></title>
<script src="jquery-1.11.1.min.js"></script>
<script >function GetJSon() {
var obj = {};
obj.UserName = $("#txt").val();
$.ajax({
type: "POST",
url: "http://someurl.net/webservices/default.aspx/ValidateUser",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
data: JSON.stringify(obj),
success: function (msg) {
console.log();
alert(msg.d)
$("#test").html(msg.d)
},
error: function () {
console.log();
}
});
}</script>
</head>
<body>
<input type="text" value="demo" id="txt" />
<input type="button" onclick="GetJSon()" value="jSon" />
Response : <div id="test">
</div>
</body>
</html>