以JSON格式返回异常消息

时间:2018-10-30 05:49:02

标签: c# wcf faultcontract

我正在研究WCF应用程序,该应用程序在生产中运行良好。它有很多服务方法。现在,要求将配置文件中的一个字段设置为true,那么它必须向消费者显示一些自定义消息。

我创建了构造函数,以确保将为每个请求都调用该构造函数,并在其中检查该配置键,并按如下所述抛出FaultException

public RESTService()
{
    if (ConfigurationManager.AppSettings("BlockLogin") == "1")
        throw new FaultException("Application under maintainance");
}

,但未在JSON中给出响应。相反,它以html格式返回,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Request Error</title>
        <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
    </head>
    <body>
        <div id="content">
            <p class="heading1">Request Error</p>
            <p xmlns="">The server encountered an error processing the request. Please see the 
                <a rel="help-page" href="http://172.16.3.156:81/_RestAPI/RESTService.svc/help">service help page</a> for constructing valid requests to the service.
            </p>
        </div>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

您不需要使用异常-正如您所看到的那样,WCF会将其转换为500服务器错误,并且不受控制。

您可以创建一个名为(例如)BusinessFault的类(普通类):

public class BusinessFault
{
 public string ErrorCode { get; set; }
 public string ErrorMessage { get; set; }
}

然后,当您想返回故障时:

if (ConfigurationManager.AppSettings("BlockLogin") == "1")
{
  return new BusinessFault() {
    ErrorCode = "0001",
    ErrorMessage = "Application under maintainance"
  }
}
相关问题