C# 使用jquery使用wcf服务
所以我尝试使用json来使用wcf服务。我希望它做的是从一个简单的html表单中获取值,并通过json将这些值分配到wcf中实例化的对象中。既然我没能做到,我就尽量缩小范围,这样你就可以(也许)帮我解决这个问题。现在,为了知道它是否有效,我希望wcf服务回答ok字符串 这是我的html/js代码C# 使用jquery使用wcf服务,c#,jquery,json,wcf,C#,Jquery,Json,Wcf,所以我尝试使用json来使用wcf服务。我希望它做的是从一个简单的html表单中获取值,并通过json将这些值分配到wcf中实例化的对象中。既然我没能做到,我就尽量缩小范围,这样你就可以(也许)帮我解决这个问题。现在,为了知道它是否有效,我希望wcf服务回答ok字符串 这是我的html/js代码 function saveSection() { $.ajax({ url: "http://localhost:52928/SectionService
function saveSection() {
$.ajax({
url: "http://localhost:52928/SectionService.svc/Guardar",
data: '{"name": "' + sectionName.value + '", "title": "' + sectionTitle.value + '", "scope": "' + sectionScope.value + '", "description": "' + sectionDescription.value + '"}',
type: "GET",
dataType: 'json',
success: function () { alert('it works') },
error: function () { alert('it doesnt work') },
contentType: "application/json",
});
}
</script>
这是区段界面
namespace WcfSection
{
[ServiceContract]
public interface ISection
{
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
string Guardar(string name, string title, string scope, string description);
}
}
最后,我认为问题可能出在web.config上
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<services>
<service name="WcfSection.SectionService" behaviorConfiguration="MyServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:52928/"/>
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" behaviorConfiguration="webHttpBehavior" contract="WcfSection.ISection"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior" />
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
<compilation debug="true"/>
</system.web>
</configuration>
我想补充一点,这是我第一次尝试这样做,而且html和服务属于不同的项目,为了达到这一点,我努力解决CORS问题。它现在所做的只是显示“它不工作”警报。我没有在我的电脑上尝试你的代码。但似乎至少你需要添加到端点行为中
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
很难猜测服务器为什么会抛出错误。我会使用Fiddler、Firebug或Chrome控制台来查看服务器的实际响应。如果您使用Firebug或Chrome,您可以在“网络”选项卡中找到响应。您可能会看到堆栈跟踪,并找到错误的根源。
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>