How to make custom WCF error handler return JSON response with non-OK http code?

前端 未结 8 1603
春和景丽
春和景丽 2020-12-04 12:36

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 (IErrorHand

8条回答
  •  春和景丽
    2020-12-04 13:07

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

提交回复
热议问题