我有一个使用JSON的WCF REST样式的服务,它在IE中效果很好,但是FireFox和Chrome令人发脾气;有关跨域调用的信息。
我遵循了这里的建议:Problem sending JSON data from JQuery to WCF REST method
但是我现在看到的是,尽管我的浏览器发送了2个请求(首先是OPTIONS,然后是POST),但POST请求根本不返回任何内容。再次,IE与此完美配合。缺少什么?
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9PVmJ0Qy5wbmcifQ==” alt =“在此处输入图像描述”>
JAVASCRIPT:
<script type="text/javascript">
function Search() {
var json = JSON.stringify($('#testForm').serializeObject());
$.ajax(
{
type: "POST",
url: "http://localhost:8000/MyService.svc/Search",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response, status, xhr) {
GetResults(response.SearchResult.QueryId);
},
error: function (xhr, status, error) {
alert("Error\n-----\n" + xhr.status + '\n' + xhr.responseText);
},
//complete: function (jqXHR, status) { alert('Status: ' + status + '\njqXHR: ' + JSON.stringify(jqXHR)); }
});
return false;
}
function GetResults(queryId) {
debugger;
$.ajax(
{
type: "GET",
url: "http://localhost:8000/MyService.svc/GetResults?queryId=" + queryId + "&ignoreXmlFeedSourceIds=",
//data: {},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (response, status, xhr) {
debugger;
DoSomethingWithResults(response);
},
error: function (xhr, status, error) {
alert(error);
},
complete: function (jqXHR, status) { alert('Status: ' + status + '\njqXHR: ' + JSON.stringify(jqXHR)); }
});
}
function DoSomethingWithResults(results) {
alert("In DoSomethingWithResults()");
// process the results here to show on UI
debugger;
};
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
SERVICE CONTRACT:
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/Search")]
SearchResponse Search(RequestInfo requestInfo);
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "/Search")]
void SearchAllowCors();
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetResults?queryId={queryId}&ignoreXmlFeedSourceIds={ignoreXmlFeedSourceIds}")]
IList<FlightJourneyAvailabilityResponse> GetResults(string queryId, string ignoreXmlFeedSourceIds);
}
我在使WCF与JSON / REST一起正常工作时遇到了许多问题。因此,我了解了新的ASP.NET Web API,它使此过程变得更加简单。对于任何新的Web服务,我可能会使用它而不是WCF。