G'day 朋友(我是美国人,但 G'day 听起来很酷)
我刚刚安装了 WCF 数据服务 5.0 包以及最新的 ASP.NET Web API 并且遇到了一个非常烦人的问题。通过在 Google 上搜索,我绝对不是唯一遇到这个问题的人,但没有一个我发现的解决方案似乎有效。
我的问题是主机应用程序不接受包含该$
字符的请求,无论我尝试什么,它都不会将请求传递给我的JsonpMediaTypeFormatter
. 因此,我不知道格式化程序是否会解决实际问题。
使用提琴手,我可以看到请求是用一个“ Accepts
”头的“ */*
”发出的,我想它不会通过我的格式化程序,我不能将“ */*
”添加到,MediaTypeHeaderValue
因为它抱怨它是一个范围。
请任何帮助或建议将不胜感激!
设置的完整描述
我创建了一个沙盒解决方案来进行测试,它由两个 ASP.NET Web 应用程序项目组成。第一个项目被调用ClientApplication
,第二个被调用HostApplication
(我相信你可以推断出哪个做了什么)。它们中的每一个都由我的本地 IIS 托管在不同的网站和 IP 地址中。我尽我所能来创建它们,就好像它们在物理上完全分离而实际上不需要服务器。
主机应用程序
有一个简单的 EDMX 文件映射到一个简单的数据库,里面有一些基本的表,没什么特别的。我也有我的服务类如下:
public class ODataService : DataService<Data.SandboxEntities>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
config.UseVerboseErrors = true;
config.SetEntitySetAccessRule("Customers", EntitySetRights.All);
config.SetEntitySetAccessRule("Employees", EntitySetRights.All);
config.SetEntitySetAccessRule("RandomDatas", EntitySetRights.All);
config.SetEntitySetAccessRule("Schedules", EntitySetRights.All);
config.SetEntitySetAccessRule("Shifts", EntitySetRights.All);
}
}
我正在使用与JsonpMediaTypeFormatter
Peter Moberg 对问题的评论中使用的相同代码:JSONP with ASP.NET Web API
最后,我JsonpMediaTypeFormatter
在Global.asax
文件中注册了我的:
protected void Application_Start(object sender, EventArgs e)
{
var config = GlobalConfiguration.Configuration;
config.Formatters.Insert(0, new JsonpMediaTypeFormatter());
}
客户端应用程序
为了将它们结合在一起,我在客户端应用程序中有一个非常简单的页面,其中包含以下代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Service Client Application</title>
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
function makeServiceCall()
{
try
{
/*
$.getJSON('http://10.10.1.7/ODataService.svc/Customers?$format=json&$callback=?',
function (response)
{
$.each(response.d, function (index, value)
{
var div = document.createElement('div');
div.innerHTML = value.ClientName;
$('#result').append(div);
})
});
*/
$.ajax({
type: "POST",
url: "http://10.10.1.7/ODataService.svc/Customers",
dataType: "json",
contentType: "application/json",
success: function (result) { alert("Winning."); },
error: function (result) { alert("Losing..."); }
});
}
catch (err)
{
alert(err);
}
}
</script>
</head>
<body>
<form id="MainForm" runat="server">
<div id="result" style="border:1px solid black;background-color:#E8E8E8;"></div>
<button onclick="makeServiceCall();return false;">Call Service</button>
</form>
</body>
</html>
您可能会注意到其中有一些带注释的 javascript。这是因为我尝试了两种不同的方法来进行服务调用(这两种方法都不起作用),我想一定要向你们说明这一点。
再次感谢!杰森