使用ajax和json对mono-hosted wcf服务进行正确配置
本文关键字:配置 服务 wcf ajax json mono-hosted 使用 | 更新日期: 2023-09-27 18:22:24
我正在制作一个WCF服务,该服务将托管在mono(CentOS 6.5)上,其中使用ajax和json从html客户端调用方法。但我无法让一个简单的例子发挥作用。
每当我调用我的方法时,服务都会返回一个错误:"预期的内容类型为'text/xml;charset=utf-8',但得到的是'application/json;charset=utf-8'"。
有人能判断我的配置是否有问题,或者mono只是不支持我在这里使用的东西吗?我在某个地方读到,如果绑定不匹配,wcf默认为text/xml,但我看不出我的绑定配置有什么问题。
这是我的ajax调用:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://PU.BL.IC.IP/wcf/DataService.svc/GetCustomers")',
data: '{"prefix": "' + $("#value").val() + '"}',
processData: false,
dataType: "json",
success: function (response) {
console.log('success');
//Do something with the result
},
error: function (a, b, c) {
// NOTE: here is where I get the error, so I know the service itself and sending the query to it works.
console.log('error');
console.log('Service call failed: ' + a.status + ' ' + a.statusText);
}
});
这是我的界面:
[ServiceContract]
public interface IDataService
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
string GetCustomers(string prefix);
}
这是我的服务实现:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DataService : IDataService
{
public string GetCustomers(string prefix)
{
List<object> customers = new List<object>();
customers.Add(new
{
Id = "1",
Name = "Customer Name",
});
return (new JavaScriptSerializer().Serialize(customers));
}
}
这是我的整个web.config:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
<customErrors mode="Off"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webscriptBehavior">
<enableWebScript/>
</behavior>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="serviceBehavior" name="DataService">
<endpoint address="" binding="webHttpBinding" contract="IDataService" behaviorConfiguration="webscriptBehavior"/>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
谢谢大家,奥利
使用RequestFormat属性装饰方法,并将其设置为JSON。
RequestFormat = WebMessageFormat.Json,
或者,将您的请求发送为xml,这是默认格式。