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

前端 未结 8 1623
春和景丽
春和景丽 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:06

    For those using web apps to call WFC, always return your JSON as a Stream. For errors, no need for a bunch of fancy/ugly code. Just change the http status code with:

    System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.InternalServerError
    

    Then instead of throwing the exception, format that exception or a custom error object into JSON and return it as a System.IO.Stream.

提交回复
热议问题