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

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

问题描述

我正在使用WCF和WebHttpBinding实现一个RESTful Web服务。目前我正在处理错误处理逻辑,实现一个自定义错误处理程序(IErrorHandler);目的是让它捕获操作抛出的任何未捕获的异常,然后返回一个JSON错误对象(包括错误代码和错误消息 - 例如{errorCode:123,errorMessage:bla})返回到浏览器用户以及一个HTTP代码,如BadRequest,InteralServerError或者其他任何东西(除了'OK'以外的任何东西)。这是我在错误处理程序的ProvideFault方法中使用的代码:

  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'。

  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。

  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身体现在有文本无法加载源代码: http:// localhost:7000 / bla ..'而不是实际的JSON数据。



任何想法?我正在考虑使用最后一个方法,只是将JSON粘贴在HTTP StatusMessage标题字段中,而不是在正文中,但是这似乎不是很好吗?



这是我的ErrorMessage类:

  [DataContract] 
public class ErrorMessage
{
public ErrorMessage(异常错误)
{
Message = error.Message ;
StackTrace = error.StackTrace;
异常= error.GetType()。名称;
}

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

结合上面的最后一个片段:

  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。谢谢。 :)


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);

--> 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);

--> 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;

--> 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..

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?

解决方案

Actually, this works for me.

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; 

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

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

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