WebFaultException to pass back an XML message rather than string? - wcf

In my RESTful services layer, any exceptions that bubble up to me are caught as Fault Exceptions. Within that FaultException, there's a custom XML message that contains <errorNumber>, <errorCode> and a <message>. I re-package the exception as a WebFaultException so I can set the HttpStatusCode for the response header to 400, 401, 404, etc.
However, I don't want to use WebFaultException<string>(string message, HttpStatusCode code). I want the message to also be an XML message.
Anyone seen how to set the HttpStatusCode of the response message AND set an XML message? I'm using Fiddler to examine my response headers and any messages that come up from the service.

What I did to get around this was create a new class MyException with simple properties and used WebFaultException<MyException> and it works nicely. I found the solution at the following link: http://www.c-sharpcorner.com/UploadFile/ankithakur/ExceptionHandlingWCF12282007072617AM/ExceptionHandlingWCF.aspx

Related

FromForm annotation not supported in MapPost()ed methods?

.NET 6, purely WebAPI project. I have an endpoint method that is expecting a urlencoded form in the POST data. The method is added to the routing table by app.MapPost("/myendpoint", MyClass.MyEndpoint) in the program's startup file; it's not in a controller. The method currently goes:
[Consumes("application/x-www-form-urlencoded")]
[HttpPost]
public static async Task<IResult> MyEndpoint([FromForm]FormData TheForm)
where FormData is a record with the expected form fields.
I've tried some other annotations. The framework just won't let me consume the form. When invoked, the method either returns HTTP error 415, or, in some iterations, an exception is thrown somewhere in the pipeline saying that "Expected a supported JSON media type but got "application/x-www-form-urlencoded"."
Is urlencoded form parameter binding even supported in WebAPI? I would even settle for the form contents as a string, won't mind parsing myself (HttpUtility.ParseQueryString to the rescue).
For the time being, I read Request.Body from the HTTP context' request body, but that's crude and also error prone, as the context is known to go poof sometimes in async methods.
EDIT: also tried placing .Accepts<FormData>("application/x-www-form-urlencoded") on the MapPost() line. Same result.
Tried replacing the body parameter with [FromBody]byte [] Body, [FromBody]string Body.

How to assert grpc method response body

I'm verifying response of a grpc service method.
Right now im asserting response by taking out every parameter and verifying it against my expected test parameter.If there are many parameters to assert, it becomes a tedious process.
So im looking for something like 'Json comparator' which will verify my grpc response message with expected message .
I'm also thinking of converting my expected and my actual messages to json and verifying it using json comparator.But this is not straightforward.
So any other thoughts?
Protobuf messages override equals(), so you can hard-code the expected response message and use normal assertEquals(expected, actual) in JUnit.

Bypassing Play's HttpErrorHandler for 4xx errors

I'm writing a microservice in Play. I'd like my controller to be able to generate client errors (4xx) with a particular JSON response body. However, Play's default HttpErrorHandler kicks in, and replaces my response body with an HTML document.
How can I have my response returned to the client untouched?
I have looked into providing a custom HttpErrorHandler, but this doesn't give access to the response that my controller had generated; the signature is:
def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result]
Edit: I can no longer reproduce this problem. Now, the error handler doesn't kick in -- which is the behaviour I'd expect. Most likely some form of user confusion / error.
A client error is a condition which is caused by the client, and Play doesn't know how to handle. That includes malformed headers, non-existing resources (read : No route available for that path).
In all cases, this won't hit a controller : It's handled before it's routed. That also means there is no body that can be passed along.
If it does hit a controller, you're free to return a Result with the proper response code and body. If it doesn't hit a controller, and the error handler is invoked, you need to return a response based on the request itself.
An example of what you're trying to achieve would be handy, since it's a bi t unclear to me.

CommunicationException - retrieve corresponding XML response?

My web service call sometimes results in CommunicationExceptions due to the fact, that the called service returns an invalid SOAP response. The exception message is:
Server returned an invalid SOAP Fault. Please see InnerException for more details.
The inner exception has the following message:
No characters can appear before the XML declaration. Line 10, position 21.
But how to obtain the response so I can log it and see myself what kind of malformed XML has been returned?
Enable message logging: https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx
You might be interested in `logMalformedMessages' attribute.
If you don't see anything useful on the client side you can try enabling the same on the server side to see what messages are leaving the server.

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

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 programmer.
The simple API for retrieving and editing resources is matched by an almost equally simple set of possible error responses, and I can’t help feeling that to keep to a “pure” RESTful approach I may be cutting my nose off to spite by face, or more specifically, the nose of my web service consumers. I could be wrong, but there doesn’t seem to be very many Http error codes that I can use, and no ways to pass back a custom error message.
To clarify, I am talking about proper exceptional errors and not expected errors. I want to actually communicate a problem to the user to help them identify what they need to do to correct it.
Possible options I am considering...
Just use the Http error codes – This seem like it would be too restrictive in what I am able to express, and won’t allow me to supply a custom message. Please(!) correct me if I am wrong.
Always return Http Success but return custom error objects – Obviously the most flexible but certainly not the most RESTful.
I would really appreciate it if anyone could share some real world experience of this particular problem.
Update
Thanks for the suggestion of using the StatusDescription property of the OutgoingWebResponseContext object. It seemed at first to be something that I could use.
I have come to the conclusion that my second option above is not for me. I want to stick to the what Http can give me.
I am having problems getting it to work, however. Regardless of the value I supply for this property, it doesn’t get returned in the response.
My service method looks like this
public MyType GetMyTypes(string criteria)
{
try
{
return GetMyTypes();
}
catch (Exception ex)
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = HttpStatusCode.Forbidden;
response.StatusDescription = "A Big fat error occurred";
return null;
}
}
And here is the raw response message. There is no mention of the custom message...
HTTP/1.1 403 Forbidden
Server: ASP.NET Development Server/9.0.0.0
Date: Wed, 07 Jan 2009 14:01:20 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Length: 0
Connection: Close
It's not as if I just need to access the correct property on the client. The information is simply not being sent across the link.
What does this StatusDescription property actually do?
Update
I never did find out how to set the StatusDescription property. I ended up not including any error message at all, and going solely with the Http status codes. I have chosen to expose both Soap and Restful endpoints for my services, and so clients can choose which they prefer to use – the simple Restful messages or the relatively richer Soap messages.
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
Send the proper response code and you can supply the custom error message in the body of the response.
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;
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.
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