1

我正在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>
4

1 回答 1

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"
  }
}
于 2018-10-30T06:24:29.780 回答