WCF 4.0 - Returning JSON WebFaultException with REST Service Template

后端 未结 3 845
名媛妹妹
名媛妹妹 2021-02-02 03:34

I am using the WCF REST Service Template 40(CS). I am throwing WebFaultExceptions as such:

throw new WebFaultException(\"Error Message\", HttpStatu         


        
相关标签:
3条回答
  • 2021-02-02 04:18

    In you web.config set the value of AutomaticFormatSelectionEnabled to false

    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" />
    

    Set the response format to json (which you have done already)

    [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json)]
    
    0 讨论(0)
  • 2021-02-02 04:25

    for those still having this issue. This worked for me

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
    throw new System.ServiceModel.Web.WebFaultException<Response>(
              new Response(false,"was not found", ""),System.Net.HttpStatusCode.BadRequest);
    
    0 讨论(0)
  • 2021-02-02 04:36

    When WebHttpBehavior.FaultExceptionEnabled is set to true, WebFaultException will result in a 200 response with the fault rendered as XML and not JSON, despite the automaticFormatSelectionEnabled configuration setting or response format attribute settings. The MSDN documentation does not mention this and is misleading in that it states that this property is only related to the 500 response code.

    0 讨论(0)
提交回复
热议问题