我试图让 WebFaultException 以 json 和 xml 的形式返回,这取决于客户端的要求,如
中所述我的服务界面是这样的
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "session_record?id={id}&command={command}")]
void SessionRecord(Guid id, String command);
异常
throw new WebFaultException<string>("Session not started", HttpStatusCode.Conflict);
Web.config 服务设置
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" faultExceptionEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
我的客户调用该服务
$.ajax({
url: "Webservice/session_record?id={id}&command={command}".format({ id: $("#sessionGuid").val(), command : "start" }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Started");
}
});
除了从服务器接收 json,我得到的是 xml
当我在我发布的链接中阅读它时,我应该可以
With the WebFaultException, the detail of the exception that is serialized in the body of >the response message will always be in the format (XML or JSON) that the client would have >received had there not been an error. If the client was expecting XML, the client will >get the exception detail serialized as XML. Likewise, if the client was expecting JSON, >the client will get the exception detail serialized as JSON.
最佳答案
我找到了解决方案; faultExceptionEnabled 需要为 false。现在我得到了 json 中的异常。
关于c# - WCF WebHttp 服务中的错误处理,仅带有 WebFaultException xml 格式的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8167202/