简体   繁体   English

WCF服务返回JSON格式的错误

[英]WCF service to return JSON-formatted faults

Is it possible to get a WCF service to return a 'fault' to the client? 是否有可能获得WCF服务以向客户端返回“错误”? I'm led to believe this is possible when using SOAP, but I'd like to be returning JSON. 在使用SOAP时我会相信这是可能的,但我想返回JSON。

Ideally, the HTTP response code would be set to something to indicate that an error occured, and then details of the problem would be available in the JSON response. 理想情况下,HTTP响应代码将被设置为表示发生错误的内容,然后在JSON响应中可以获得问题的详细信息。

Currently, I'm doing something like this: 目前,我正在做这样的事情:

[ServiceContract]
public class MyService
{
    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    [FaultContract(typeof(TestFault))]
    public MyResult MyMethod()
    {
        throw new FaultException<TestFault>(new TestFault("Message..."), "Reason...");
    }
}

Where TestFault looks like this: TestFault如下:

[DataContract]
public class TestFault
{
    public TestFault(string message)
    {
        this.Message = message;
    }

    [DataMember]
    public string Message { get; set; }
}

There's nothing particularly special in the service configuration at the moment. 目前服务配置没有什么特别之处。

This results in a '400 Bad Request' response, with an HTML-formatted error. 这会导致“400错误请求”响应,并出现HTML格式错误。 (When I includeExceptionDetailInFaults , I can see the 'Reason...' and details of the FaultException , but no details on the TestFault .) (当我includeExceptionDetailInFaults ,我可以看到'Reason ...'和FaultException详细信息,但没有关于TestFault详细信息。)

The web service returns JSON ok when an Exception (or FaultException ) isn't being thrown. 当没有抛出Exception (或FaultException )时,Web服务返回JSON ok。

Any suggestions..? 有什么建议..?

All what you need is possible starting with .NET 4. see here for details. 所有您需要的东西都可以从.NET 4开始。有关详细信息,请参阅此处 For example: 例如:

throw new WebFaultException<string>(
    "My error description.", HttpStatusCode.BadRequest); 

Edit: fixed link + added summary. 编辑:固定链接+添加摘要。

You can find an explanation and a solution here 您可以在此处找到解释和解决方案

To summarize the solution from the link, extend WebHttpBehavior and override AddServerErrorHandlers in order to add your own implementation of IErrorHandler. 要从链接中总结解决方案,请扩展WebHttpBehavior并覆盖AddServerErrorHandlers,以便添加自己的IErrorHandler实现。 This implementation will extract the error from the service call and generate fault information. 此实现将从服务调用中提取错误并生成故障信息。

The linked article also shows how to write your own Service Host Factory that sets up this behavior. 链接的文章还说明了如何编写自己的服务主机工厂来设置此行为。

The error callback of your jQuery.ajax() call should look like this: 您的jQuery.ajax()调用的错误回调应如下所示:

error: function (xhr, status, error) {
  var responseObj = JSON.parse(xhr.responseText);
  alert('Request failed with error: "' + responseObj.Message);
}

In your WCF Service, pass an exception to the WebFaultException constructor. 在WCF服务中,将异常传递给WebFaultException构造函数。 Your custom message will be accessible via responseObj.Message in the above javascript: 您可以通过上面的javascript中的responseObj.Message访问您的自定义消息:

public class AJAXService : IAJAXService
{
  public void SomeMethod()
  {
    throw new WebFaultException<Exception>(new Exception("some custom error message!"), HttpStatusCode.InternalServerError);
  }
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM