我在 .NET 4 平台上创建了一个 WCF 服务,当我使用 jquery ajax POST 访问它时,它会返回 JSON。我遇到的问题是,如果 POST 的 json 响应不包含在带有 Result 后缀的方法的名称中,我会更喜欢。
详细地:
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
Person GetInfo(string id);
}
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class Service: Iservice
{
public Person GetInfo(string id)
{
...
return new Person();
}
}
public class Person
{
public string FirstName;
public string LastName;
public Person(){
FirstName = "Jon";
LastName = "Doe";
}
}
web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding"
contract="IService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
jQuery:
var myparameters = JSON.stringify({ id: $('#id').val()});
$.ajax({
type: "POST",
url: "/Service.svc/GetInfo",
data:myparameters,
contentType: "application/json",
dataType: "json",
success: function (response) {
...
}
}
});
在BodyStyle = WebMessageBodyStyle.Wrapped
我的javascript代码中得到的响应是:
{"GetInfoResult" : {"FirstName":"Jon", "LastName":"Doe"}}
但是当我将其更改为WebMessageBodyStyle.Bare
其他所有内容保持不变时,会发生 500 内部服务器错误。
是否可以在没有 Method+Result 包装器的情况下在我的 POST 响应中返回 Bare json?如果是,我做错了什么?
提前致谢