Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WCF 4.0-使用REST服务模板返回JSON WebFaultException_C#_.net_Wcf_Exception_Rest - Fatal编程技术网

C# WCF 4.0-使用REST服务模板返回JSON WebFaultException

C# WCF 4.0-使用REST服务模板返回JSON WebFaultException,c#,.net,wcf,exception,rest,C#,.net,Wcf,Exception,Rest,我正在使用WCF REST服务模板40(CS)。我抛出如下例外情况: throw new WebFaultException<string>("Error Message", HttpStatusCode.BadRequest); 我仍然无法将异常作为JSON返回 编辑添加签名了解更多信息: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, Respons

我正在使用WCF REST服务模板40(CS)。我抛出如下例外情况:

throw new WebFaultException<string>("Error Message", HttpStatusCode.BadRequest);
我仍然无法将异常作为JSON返回

编辑添加签名了解更多信息:

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, UriTemplate = "myendpoint")]

有没有一种简单的方法可以实现这一点?

在web.config中,将AutomaticFormatSelectEnabled的值设置为false

<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />

WebHttpBehavior.FaultExceptionEnabled
设置为
true
时,
WebFaultException
将导致200响应,故障呈现为XML而非JSON,尽管
AutomaticFormatSelectEnabled
配置设置或响应格式属性设置无效。MSDN文档中没有提到这一点,并且具有误导性,因为它指出此属性仅与500响应代码相关。

对于仍存在此问题的用户。这对我有用

WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
throw new System.ServiceModel.Web.WebFaultException<Response>(
          new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);
WebOperationContext.Current.OutgoingResponse.ContentType=“application/json”;
抛出新System.ServiceModel.Web.WebFaultException(
新响应(false,“未找到”,“System.Net.HttpStatusCode.BadRequest”);

如果此操作正常,则状态代码应为400(错误请求)。是否可以启用跟踪以查看是否有其他原因阻止处理WebFaultException?我刚刚用REST服务模板创建了一个新项目,将(ResponseFormat=WebMessageFormat.Json)添加到其中一个操作中,并添加了与您相同的行-响应返回时编码为Json,而不是XML。是否我在代码中这样做:
catch(WebFaultException ex){throw;}
?如果需要,我还可以添加额外的配置信息;你能发布操作合同的签名吗(带有[WebGet/WebInvoke]属性)?我添加了我的方法签名。它们都是POST,并且具有类似的设置。将
WebHttpBehavior.FaultExceptionEnabled
设置为
false
对我很有帮助。否则,每次抛出
WebFaultException
时,我都会得到500个响应代码。什么是
response
[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
throw new System.ServiceModel.Web.WebFaultException<Response>(
          new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);