5 c# ajax wcf jquery xmlhttprequest
我正在创建一个将返回json对象的WCF Web服务,但是当我尝试进行AJAX调用时,我仍然遇到400错误请求错误:
OPTIONS http://localhost:55658/WebServiceWrapper.svc/GetData?_=1318567254842&value=97 HTTP/1.1
Host: localhost:55658
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
DNT: 1
Connection: keep-alive
Origin: http://localhost:3000
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Fri, 14 Oct 2011 04:40:55 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Length: 0
Connection: Close
Run Code Online (Sandbox Code Playgroud)
这是我的AJAX调用:
$.ajax({
contentType: 'application/json',
url: 'http://localhost:55658/WebServiceWrapper.svc/GetData',
dataType: 'json',
data: {
value: 97
},
success: function (data) {
alert('success' + data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('failure' + errorThrown);
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的WCF服务定义:
public class WebServiceWrapper : IWebServiceWrapper
{
public object GetData(int value)
{
return new
{
ReturnValue = string.Format("You entered: {0}", value)
};
}
}
Run Code Online (Sandbox Code Playgroud)
它的界面:
[ServiceContract]
public interface IWebServiceWrapper
{
[OperationContract]
object GetData(int value);
}
Run Code Online (Sandbox Code Playgroud)
我知道我之前已经解决了这个问题,但我不记得以前做过什么.任何帮助都会非常感激,因为我放在墙上的洞越来越大了.
您可能需要做几件事(或检查您是否已完成):
您的 GetData OperationContract 需要用 [WebGet] 属性进行修饰。
[WebGet]
[OperationContract]
object GetData(int value);
Run Code Online (Sandbox Code Playgroud)
您的 WebServiceWrapper 类需要使用 [AspNetCompatibilityRequirements] 属性进行修饰(添加对 System.ServiceModel.Web 的引用以使其可用)
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WebServiceWrapper : IWebServiceWrapper
Run Code Online (Sandbox Code Playgroud)
GetData 操作的返回值需要进行包装。一个简单的方法是使用 JavaScriptSerializer 将对象序列化为 json
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new
{
ReturnValue = string.Format("You entered: {0}", value)
});
Run Code Online (Sandbox Code Playgroud)
您需要确保在端点(客户端和服务)中使用 [webHttpBinding]
<endpoint ... binding="webHttpBinding" ... />
Run Code Online (Sandbox Code Playgroud)
我不知道接下来的事情是否是强制性的,但您可能需要一个启用 Web 脚本的端点行为
<endpointBehaviors>
<behavior name="[endpointBehaviorName]">
<enableWebScript/>
</behavior>
</endpointBehaviors>
Run Code Online (Sandbox Code Playgroud)
显然,您需要在端点中引用此行为配置
<endpoint ... behaviorConfiguration="[endpointBehaviorName]" ... />
Run Code Online (Sandbox Code Playgroud)