【发布时间】:2018-05-29 17:12:22
【问题描述】:
我在 WCF RESTful 服务中有以下代码
public EmployeeJSON GetEmployeeJSON(string id)
{
List<EmployeeJSON> employees = new List<EmployeeJSON>()
{
new EmployeeJSON() {Name="Sumanth",Id=101,Salary=5000.00 },
new EmployeeJSON() {Name="Ehsan",Id=102,Salary=6000.00 },
};
var Employee = (from x in employees
where x.Id.ToString() == id
select x);
return Employee.FirstOrDefault() as EmployeeJSON;
}
下面是RESTful Service的声明
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetJson/{id}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
EmployeeJSON GetEmployeeJSON(string id);
当我在浏览器中执行以下 URL 时
http://localhost:1249/Service1.svc/GetJson/101
我得到如下结果
{"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}
但是当我从 jQuery 调用时,代码会出错并显示空消息
$(document).ready(function () {
});
var GetJson = function () {
$.ajax({
type: "GET",
url: "http://localhost:1249/Service1.svc/GetJson/101",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (data) {
var result = data.GetEmployeeJSONResult;
var id = result.Id;
var name = result.Name;
var salary = result.Salary;
$('#jsonData').html('');
$('#jsonData').append('<table border="1"><tr><th>Employee Id</th><th>Name</th><th>Salary</th></tr><tr><td>' + id + '</td><td>' + name + '</td><td>' + salary + '</td></tr></table>');
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
下面是代码,我放在WCF RESTful Service的web.config中
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
我在这里错过了什么?
【问题讨论】:
-
您是否也可以添加
xhr变量的全部数据(来自您的错误块)? -
请查阅规范和数百篇关于此的文章。
Access-Control-Allow-Origin只是您必须包含的 一个 标头,通常还有其他标头。 -
打开浏览器开发控制台,看看究竟是什么请求和响应。我的疯狂猜测是响应将是 405 方法不允许。