我已经搜索了几个小时并尝试了不同的方法来使其发挥作用。我在 stackoverflow 上尝试了很多文章,要么是我太蠢了,无法让事情正常工作,要么是我有一些独特而奇怪的配置,阻碍了我体验快乐。
我创建了本教程概述的 WCF 服务:
http://www.codeproject.com/Articles/97204/Implementing-a-Basic-Hello-World-WCF-Service
它是超级基本的并且有一种方法,我想要它做的就是允许我使用 json 通过 jQuery.AJAX() 来使用它。
我把它托管在 IIS 中并且可以正常工作。我可以毫无问题地访问 WSDL。
我尝试使用以下代码来使用它:
$.ajax({
dataType: 'json',
type: 'POST',
contentType: "application/json",
url: "//localhost:546/HelloWorldService.svc/GetMessage",
data: {
name: "Joe"
}
}).done(function(msg){
console.log(msg);
$("#result").append(msg);
});
我总是出错。根据我的尝试,我收到了 500 个错误、402 错误、有关不正确内容的错误......所有错误。
我尝试实施以下文章中的解决方案。它们的范围从让我更改 web.config 端点(我知道我必须更改它们,但到目前为止我尝试过的所有方法都无法在添加 JSON 端点方面起作用)到添加诸如
[WebInvoke(Method = "POST", UriTemplate = "json/PostSalesOrderData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
到界面。
以下是我看过的一些文章,并试图深入研究我的解决方案以使其正常工作,但没有取得太大成功。
Phonegap Android 上的 Javascript JSON 和 WCF Web 服务
HTTP/1.1 415 无法处理消息,因为内容类型为“application/json;” charset=utf-8' 不是预期的类型 'text/xml;字符集=utf-8'
具有 JSON、JSONP 和 SOAP 端点的 WCF 服务
两个端点(soap、json)和一个服务方法
WCF REST 服务不接受 .Net 4 中的 JSON
我还浏览了本教程,并尝试使用他所说的内容来使我的解决方案发挥作用。依然没有!
http://www.primordialcode.com/blog/post/passing-json-serialized-objects-wcf-service-jquery
这就是我的界面的样子
[ServiceContract]
public interface IHelloWorldService
{
[OperationContract]
[WebInvoke(UriTemplate = "GetMessage", Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
String GetMessage(String name);
}
谁能帮我体验快乐?
预先感谢您甚至查看我的问题。如果您需要更多信息或者我没有提供足够的信息,请告诉我,以便我可以帮助您!
我一定是错过了一些愚蠢的东西......我知道这并不难。
EDIT:
工作 Web.Config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebHTTPEndpointBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="MyWebServiceBinding" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</webHttpBinding>
</bindings>
<services>
<service name="MyWCFServices.HelloWorldService"
behaviorConfiguration="MyServiceTypeBehaviors">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="MyWebServiceBinding" behaviorConfiguration="WebHTTPEndpointBehavior"
contract="MyWCFServices.IHelloWorldService"/>
<endpoint contract="IMetadataExchange"
binding="mexHttpBinding" address="mex"/>
</service>
</services>
</system.serviceModel>
</configuration>