我正在使用asp.net web api进行跨域json发布。在我的服务/服务器端我有以下方法,该方法响应于POST
请求:在IE,Firefox和Chrome中跨域Json发布成功,但在Firefox和Chrome上都报告为空错误
// POST api/<controller>
public HttpResponseMessage Post(Customer newCustomer)
{
DataClassesDataContext db = new DataClassesDataContext();
var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, newCustomer);
db.Customers.InsertOnSubmit(newCustomer);
db.SubmitChanges();
string uri = Url.Link("DefaultApi", new { id = newCustomer.Id });
response.Headers.Location = new Uri(uri);
return response;
}
而在客户端,它在不同的端口号(即跨域)运行,我使用以下jQuery代码:
<body>
<input type="button" value="click me" onclick="hello()" />
<script type="text/javascript">
function hello() {
//SEE: http://stackoverflow.com/questions/5241088/jquery-call-to-webservice-returns-no-transport-error
$.support.cors = true;
//var jsonObjects = [{ Name: "Name1", CellphoneNum: 1234657911 }];
$.ajax({
url: "http://localhost:26037/api/customer",
type: "POST",
crossDomain: true,
data: { Name: "Name321", CellphoneNum: 1234657922 },
dataType: "json",
success: function (result) {
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Thrown Error: ' + thrownError);
alert('xhr status: ' + xhr.status);
}
});
}
</script>
</body>
我的问题是,从客户端,IE浏览器上会显示成功警报消息和数据将被插入使用LINQ代码在我的POST方法的数据库。但是,使用Chrome或Firefox时,数据也会插入到数据库中,并且LINQ代码将成功执行,但会显示空字符串错误和0 xhr状态的消息框。
为什么它只报告Firefox和Chrome上的错误,同时数据在服务器上发布并成功处理?