当我的代码中出现异常时,我想将其作为 FaultException/WebFaultException 返回,具体取决于它是 REST 还是 SOAP。以下问题与我项目的 REST 组件有关。异常被触发,我在我的调试窗口中看到它(见图)。
我们清楚地看到 WebFaultException 正在被触发,但我在 JSON 中的响应不是 http badrequest 也不是我的异常消息,而是始终如下:
{"readyState":4,"responseText":"","status":202,"statusText":"Accepted"}
这是我的界面:
[WebInvoke(Method = "POST", UriTemplate = "/Package/", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
[FaultContract(typeof(FaultException))]
[OperationContract]
string CopyZip(Stream zippedPackage);
这是它的实现:
public string CopyZip(Stream zippedPackage)
{
try
{
ZipCreator pck = new ZipCreator();
pck.CopyUploadedZip(zippedPackage);
return "Zipped";
}
catch (Exception ex)
{
//throw new FaultException(ex.Message);
throw new WebFaultException<string>(ex.Message, HttpStatusCode.BadRequest);
}
请您参考如下方法:
我看过一些帖子,其中的问题与 WcfRestContrib 自定义错误处理有关。在这些情况下,将服务类属性从 [ServiceConfiguration("Rest", true)] 更改为 [ServiceConfiguration("Rest", false)] 最终解决了问题。或者,您可以将其保留为 true,并尝试使用 WebException 而不是 WebFaultException,如下所示
throw new
WcfRestContrib.ServiceModel.Web.Exceptions.WebException(HttpStatusCode.BadRequest, "My custom error!");
