Handling anything other than HttpStatusCode.OK - wcf

We have written a restful service using WCF and are now trying to write FitNesse tests to verify the behaviour of this service.
One test is that a 404 status code is returned if a resource can not be found.
The problem is that we can not find a mechanism for consuming the service that allows us to get the status code of the incomming response. Everything seems to work fine for everything other than 200. We have tried using HttpWebRequest and HttpWebResponse and the WebChannelFactory all of which throw exceptions of various types depending on the HttpStatusCode returned by the service.
Why can't I see the status code???!!

You can see the status code, in properties of the WebException that is thrown. You can get ex.Status. Then, you can get ex.Response, and access the status code.

Related

Handing unauthorized requests in WCF?

We have an WCF service, using webhttp binding. Users get authenticated, and then a method is called. In the method, we check a variety of settings associated with the user and some information specific to the request before knowing if the user is authorized to make the call.
Since this is WCF, I think I should be throwing a FaultException of some sort, but it's not clear if there is best practices.
My thoughts are that once I know what exception I will be throwing, I'd add a IErrorHandler which would set the headers correctly to 403.
Two questions:
1) Is there a standard FaultException for unauthorized requests? i.e. the equivalent of the http status code of 403?
2) Should I be able to handle the exceptions that I'll be throwing and change the response code to 403? Will I be able to pass through a custom error message? I've seen some posts that setting headers using the operation context in a catch does not get propagated to the client.
Ideally I'd be able to set the status to 403 with additional information like "You must be part of the administrators group to add a user"
Because you're using webhttp binding, traditional WCF fault management is not pertinent here and it's better to use WebFaultException and WebFaultException<>.
Public string MyOperation()
// Operation logic
// ...
throw new WebFaultException<string>("You must be part of the administrators group to add a user", HttpStatusCode.Forbidden);
}
As you think, it's very important to use standard HTTP status codes when developping an HTTP (REST-like) service.
It's been my experience that throwing fault exceptions, at least with wshttpbinding and basichttpbinding, can cause your web service to fail, so I don't recommend that approach.
If you want to send a message back to unauthorized users, just send an HTML response, setting the status to any one of the 400 responses that seem appropriate.
But from experience, fault exceptions, even if they're a controlled response to user actions and not from an actual processing error, will cause your web service to fail. I think they should be reserved genuine processing exceptions.
I went ahead and derived custom exceptions from FaultException, and then added an IErrorHandler to set the appropriate headers.
This seemed to be the best of both worlds. The code only throws exceptions derived from ones used in WCF, and all the handling specific to http binding is done via an IErrorHandler outside the business logic.

Exception handler in a WCF REST service

I would like to create an exception handler in a WCF REST service. For Client recesse this exception in a simple way. I found many implementations using SOAP IErrorHandler for WCF, but none for REST. Could anyone help me with this?
Did you try using WebFaultException?
the exception information is provided in response message. Usually (in HTTP GET for REST), a result is expected as XML/JSON. In case of any error the error message is places instead of REST URI result.
http://www.robbagby.com/rest/effective-error-handling-with-wcf-rest/
WCF Rest Error Handling
IErrorHandler also works for WCF REST services, although you may need to know about how a non-SOAP (e.g., JSON) message is mapped inside the WCF Message object. The example at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/07/wcf-extensibility-ierrorhandler.aspx shows an error handler used to format responses to a JS client (in JSON).

Is returning an object or an exception better in case of REST based WCF services?

We are working on developing a REST based WCF service. I was wondering if it is a good idea to always return objects from the service calls irrespective of the execution status.
If any exception would occur on the service side, then appropriate fields in that object would be populated with the exception details (error code & message), otherwise it will just have the error code field set to 0 indicating success. In our case the consumer of the service can be either Java or .NET.
In REST services we model communication, including communicating errors, on the HTTP protocol. For REST services built using WCF 4, use the WebFaultException to return error conditions from a service. This results in returning a response message to the client with the HTTP status indicating the disposition of the request.

Error Handling in WCF Rest 4.0 online template

I keep getting the 400 bad request if there is de-serialization issue / other errors. If i try to debug by setting a breakpoint in the method that gets called, it does not get hit, if there is a deserialization issue. How do I intercept this and tweak the response to give me more details.
I looked at some articles regarding webprotocolexception but I think the WCF Rest online Template and the starter kit or not the same. Is the starter kit like an add-on to the template?
thanks for your time.
Handling Exceptions in RESTful WCF Services is tough. Deserialization issues are the worst since no user code gets called. The framework handles the Exception and simply returns an error to the caller. There is a way to see those errors though. You have to configure tracing for WCF (via Web.config). Here’s a link describing the process as well as where to find the trace viewer on your machine:
Service Trace Viewer Tool (SvcTraceViewer.exe)
Unfortunately there's no way to tweak that behavior. For other Exceptions, though, you can implement a custom HttpBehavior (or HttpBehavior2 if you're using the REST Starter Kit) with a custom IErrorHandler implementation to handle the Exceptions.
Error 400 means bad request => it is picked up at WCF level and does not even reach the method. So you need to look at the request and if you are passing JSON, fast chance it is in wrong format.
I had a personal project that I implemented in WCF REST and had to battle with this error which was quite frustrating. Also error handling on the server and returning error codes to the client is atrocious since you cannot return text content and all I have is HTTP error code and error description (first line in the HTTP response). I will never ever use WCF REST again as it is a bodged implementation.

Implement 'Ping' functionality using Message Inspector causes WCF runtime to throw NullReferenceException

I'm using WCF to implement a web service. This web service requires a 'ping' feature as a health monitor for each service. This functionality has been implemented using IDispatchMessageInspector and is configured for each endpoint of a service. This is due to a business requirement for the 'ping' to be as near the actual service code as possible. At the same time, I did not want to tie it to each service implementation's code and IDispatchMessageInspector seems to be a good fit.
The service uses a Request-Reply MEP. Each request message contains an element that specifies what processing is required. The service will then use this value to determine how to process the data in the message. The same element is used to define a request message as a 'heartbeat' check.
The 'ping' message inspector will pre-process a request message in the AfterReceiveRequest() method and if it determines the request is a 'heartbeat', it will then generate the correct response and pass that on to the BeforeSendReply() method via a correlation object returned from AfterReceiveRequest(). The request message parameter of AfterReceiveRequest(), which is by reference, is then set to null to prevent the message from being processed by the service implementation code.
The technique of setting request message to null was found in a web site or blog which I can't remember nor find the URL for. This technique works great on it's own and I can prevent service implementation code from being executed if it's a 'heartbeat' request.
Unfortunately, setting the request message to null in a message inspector will cause the WCF runtime to always throw a NullReferenceException. From the stack trace, I gather the runtime will still pass the message object (which will be null after going through 'Ping' message inspector) to the dispatcher and when the dispatcher tries to deserialise a null message object, causes the NullReferenceException.
However, my system also implements IErrorHandler to catch any unhandled exceptions in the service and log it. This means every successful 'heartbeat' request will generate a log entry for the NullReferenceException and the 'heartbeat' could be as frequent as every minute.
The Question :
What can I do to prevent logging of 'useless' NullReferenceException thrown when 'Ping' prevents service implementation code from running by setting request to null.
Many thanks in advance.
~hg
Not the most graceful solution but potential workarounds (that i've not tested), but where you detect your ping calls in the inspector code, could you not throw your own custom exception type i.e. PingRequestException, and handle this when it returns to the client? Would that avoid you hitting the WCF Runtime code, thus avoiding the logging of unhandled exceptions.
Otherwise you could try to use a base service, inherited by all of your services (the other side of the wcf runtime code) that detects and handles ping requests in the constructor before hitting the actual service code.