如何使自定义 WCF 错误处理程序返回带有非 OK http 代码的 JSON 响应? [英] How to make custom WCF error handler return JSON response with non-OK http code?

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

问题描述

我正在使用 WCF 和 WebHttpBinding 实现 RESTful Web 服务.目前我正在研究错误处理逻辑,实现自定义错误处理程序 (IErrorHandler);目的是让它捕获操作抛出的任何未捕获的异常,然后返回一个 JSON 错误对象(包括错误代码和错误消息 - 例如 { "errorCode": 123, "errorMessage": "bla" })返回给浏览器用户以及一个 HTTP 代码,例如 BadRequest、InteralServerError 或其他任何东西(实际上除了OK"之外的任何东西).这是我在错误处理程序的 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: application/json,但是状态代码是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);

--> 这会返回正确的状态代码,但是内容类型现在是 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;

--> 这将返回正确的状态代码和正确的内容类型!问题是 http 正文现在有文本 'Failed to load source for: http://localhost: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 错误处理程序返回带有非 OK http 代码的 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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