【发布时间】:2014-04-23 13:58:24
【问题描述】:
所以我正在尝试使用 json 来使用 wcf 服务。我想要它做的是从一个简单的 html 表单中获取值,并通过 json 将这些值分配到 wcf 中实例化的对象中。由于我无法这样做,所以我尽可能地缩小它,所以你可以(也许)帮助我解决这个问题。现在,只是想知道它是否有效,我希望 wcf 服务回答一个 ok 字符串。
这是我的 html/js 代码
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>
这是我的服务
public class SectionService : ISection
{
public string Guardar(string name, string title, string scope, string description)
{
return "OK";
}
}
这是部分界面
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 问题。它现在所做的只是显示“它不起作用”警报。
【问题讨论】:
-
很难猜出为什么服务器会抛出错误。我会使用 Fiddler、Firebug 或 Chrome 控制台来查看来自服务器的实际响应。如果您使用 Firebug 或 Chrome,您可以在“网络”选项卡中找到响应。您也许能够看到堆栈跟踪并找到错误的根源。