What is the best way to return errors from a WCF service in a RESTful way?

前端 未结 5 1672
谎友^
谎友^ 2020-12-04 18:11

Using WCF in a RESTful way seems great. I’m a big fan of the big guns like simplicity and flexibility, but I also love the way the Urls end up looking. What can I say, I’m a

相关标签:
5条回答
  • 2020-12-04 18:30

    Send the proper response code and you can supply the custom error message in the body of the response.

    0 讨论(0)
  • 2020-12-04 18:38

    See this thread for a similar question.

    In a nutshell I believe you can set the HTTP status code (to one of the error codes), and provide your custom message in the StatusDescription property:

    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
    response.StatusCode = System.Net.HttpStatusCode.Forbidden;
    response.StatusDescription = "Custom";
    

    I don't know much about the prevalence of this technique in the real world unfortunately.

    0 讨论(0)
  • 2020-12-04 18:41

    With .net 4, throw a WebFaultException<T>(T errorDetail, HttpResponseCodecode)

    Here you set your response type to another object type, which makes sense, and also you set the ResponseCode that you want.

    The errorDetail must be serializable

    http://blogs.msdn.com/b/endpoint/archive/2010/01/21/error-handling-in-wcf-webhttp-services-with-webfaultexception.aspx

    0 讨论(0)
  • 2020-12-04 18:48

    I add the error code both as above (in the status description) and in the body of the returned page in my REST services as:

    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
    response.StatusCode = HttpStatusCode.Unauthorized;
    response.StatusDescription = "You are not authorized.";
    HttpContext.Current.Response.Write("You are not authorized.");
    return null;
    
    0 讨论(0)
  • 2020-12-04 18:50

    This may be a defect. As of 9/22/2011, the issue is under review by the product team:

    http://connect.microsoft.com/VisualStudio/feedback/details/690162/wcf-rest-custom-outgoingwebresponsecontext-statusdescription-not-returned-in-response

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