asp.net - 从 WCF 中的 ASP.NET RESTful Web 服务返回错误的最佳实践

标签 asp.net wcf

这是我的服务代码。正如所有最佳实践文章所建议的那样,我以 WebFaultException 的形式抛出错误。

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class API
{
    [OperationContract]
    [WebGet()]
    public int MyMethod()
    {
        throw new WebFaultException<string>("TESTERROR", HttpStatusCode.BadRequest);
    }
}

现在,当向 http://localhost:1389/API.svc/MyMethod 发送请求时,我得到的就是这个 JSON 对象:

{"ExceptionDetail":null,"ExceptionType":null,"Message":"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.","StackTrace":null}

我尝试在 web.config 中启用 includeExceptionDetailInFaults,消息确实发生了一些变化,但我仍然没有在任何地方看到我的“TESTERROR”!

最佳答案

我认为发生的情况是您没有发生任何类型的返回,只有响应代码。所以你的服务器在没有任何附加信息的情况下抛出 500。您仍然可以通过将异常详细信息输出到日志文件来使用它。

我通常做的是创建一个可序列化的响应对象,其中包含一条消息以及我想要返回给客户端的任何代码。然后我捕获异常,构建响应对象并将其返回给客户端。然后客户端会收到一个可以读取的 xml 有效负载。因此,如果它不是 200(正常),那么我会将其视为错误并显示相应的消息(或我在 xml 中包含的详细信息。

<ServiceError>
   <ServerCode>
      500
   </ServerCode>
   <ApplicationCode>
      9100
   </ApplicationCode>
   <Message>
      API key is expired.
   </Message>
</ServiceError>

更新:

就 JSON 标准而言,我从未见过实际的文档标准。我所看到的是一种事实上的标准,或者更确切地说是一种趋势:

{
  "status": "success", //or "failed"
  "data": {
    //any app specific payload here
  },
  "message": null //or additional info here (i.e. exception details)
}

关于asp.net - 从 WCF 中的 ASP.NET RESTful Web 服务返回错误的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13076445/

相关文章:

.net - 我应该在HttpCookie.Expires和HttpCachePolicy.SetExpires中使用DateTime.Now还是DateTime.UtcNow吗?

html - 浏览器缩放期间按钮内的动态文本

c# - ASP.NET 生产服务器 PDB 文件

.net - WCF 绑定(bind) - 太多了!我该如何选择?

wcf - 使用 WCF 序列化 POCO 代理

asp.net - IF 运算符与 If、then、else 之间的计算差异

javascript - Canvasjs 图表中的渲染数据

javascript - 保留通过 JavaScript 客户端的身份验证?

c# - WCF:缓存 SSL 数据

c# - 将 SoapUi 项目转换为等效的 DotNet WCF 客户端代码/配置