如何使自定义WCF错误处理程序返回JSON与非正常的HTTP code反应? [英] How to make custom WCF error handler return JSON response with non-OK http code?

查看:610
本文介绍了如何使自定义WCF错误处理程序返回JSON与非正常的HTTP code反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WCF和的WebHttpBinding实现RESTful Web服务。目前我工作的错误处理逻辑,实现自定义错误处理程序(IErrorHandler);这样做的目的是要把它赶操作抛出的任何未捕获异常,然后返回一个JSON错误对象(包括说一个错误code和错误信息 - 例如,{错误code:123的errorMessage:喇嘛})返回给浏览器用户以及一个一个HTTP code如BadRequest,InteralServerError或什么(什么比OK等真的)。这里是code我用我的错误处理程序的ProvideFault方法中:

I'm implementing a RESTful web service using WCF and the WebHttpBinding. Currently I'm working on the error handling logic, implementing a custom error handler (IErrorHandler); the aim is to have it catch any uncaught exceptions thrown by operations and then return a JSON error object (including say an error code and error message - e.g. { "errorCode": 123, "errorMessage": "bla" }) back to the browser user along with an an HTTP code such as BadRequest, InteralServerError or whatever (anything other than 'OK' really). Here is the code I am using inside the ProvideFault method of my error handler:

fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
var rmp = new HttpResponseMessageProperty();
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);

- >此方法返回的Content-Type:应用/ JSON,但是状态code是OK,而不是InternalServerError

--> This returns with Content-Type: application/json, however the status code is 'OK' instead of 'InternalServerError'.

fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);
var rmp = new HttpResponseMessageProperty();
rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
//rmp.Headers.Add(HttpRequestHeader.ContentType, "application/json");
fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);

- >此方法返回正确的状态code,但内容类型现在是XML。

--> This returns with the correct status code, however the content-type is now XML.

fault = Message.CreateMessage(version, "", errorObject, new DataContractJsonSerializer(typeof(ErrorMessage)));
var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

var response = WebOperationContext.Current.OutgoingResponse;
response.ContentType = "application/json";
response.StatusCode = HttpStatusCode.InternalServerError;

- >此方法返回正确的状态code和正确的内容类型!问题是,在HTTP的身体现在有文字无法加载源:的http://本地主机:7000 / BLA ..而不是实际的JSON数据。

--> This returns with the correct status code and the correct content-type! The problem is that the http body now has the text 'Failed to load source for: http://localhost:7000/bla..' instead of the actual JSON data..

任何想法?我正在考虑使用最后一种方法,只是坚持的JSON在HTTP StatusMessage头字段,而不是在身,但这似乎不是很漂亮?

Any ideas? I'm considering using the last approach and just sticking the JSON in the HTTP StatusMessage header field instead of in the body, but this doesn't seem quite as nice?

推荐答案

其实,这对我的作品。

下面是我的ErrorMessage类:

Here's my ErrorMessage class:

    [DataContract]
    public class ErrorMessage
    {
        public ErrorMessage(Exception error)
        {
            Message = error.Message;
            StackTrace = error.StackTrace;
            Exception = error.GetType().Name;
        }

        [DataMember(Name="stacktrace")]
        public string StackTrace { get; set; }
        [DataMember(Name = "message")]
        public string Message { get; set; }
        [DataMember(Name = "exception-name")]
        public string Exception { get; set; }
    }

加上最后片段上面:

Combined with the last snippet above:

        fault = Message.CreateMessage(version, "", new ErrorMessage(error), new DataContractJsonSerializer(typeof(ErrorMessage)));
        var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);
        fault.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

        var response = WebOperationContext.Current.OutgoingResponse;
        response.ContentType = "application/json";
        response.StatusCode = HttpStatusCode.InternalServerError; 

这给了我正确的错误,JSON。谢谢。 :)

This gives me proper errors as json. Thanks. :)

这篇关于如何使自定义WCF错误处理程序返回JSON与非正常的HTTP code反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆