3

I have a very simple WCF web service which I call on the client side using Ajax:

Here is my web service:

public string TestService() {
    throw new Exception();
    return "";
}

Here is what my client side Ajax call looks like:

var mySuccess = function(result,statuscode,xhr){
    alert('success');
}

var myFail = function(result,statuscode,xhr){
    alert('failure');
}

$.ajax({
    type: 'Post'
    contentType: "application/json; charset=utf-8",
    url: '../myService.svc/TestService',
    data: '',
    dataType: "json",
    success: mySuccess,
    error: myFail
});

This web service fails every time (as it should!), returning a status and code of '500: internal server error'. The 'myFail' callback function is fired as it should.

However, if I modify the response header within my web service, like so:

public string TestService() {
    WebOperationContext.Current.OutgoingResponse.Headers.Add("token", "1");
    throw new Exception();
    return "";
}

then the status/code returned is '200: OK', every time!

This means that the 'mySuccess' function is fired every time, even when the web service should be failing. I can't figure out why simply adding my own custom header to the response would overwrite the return status in this way.

Is there something I am missing?

5
  • I am able to reproduce the behavior. Looks like a bug. May 7, 2012 at 14:28
  • Thats awkward then. Is there any other way to pass some reponse back to the client - which doesn't involve fiddling with the actual return value?
    – John
    May 7, 2012 at 15:54
  • I don't think so. All that the client sees is the actual HTTP response which contains 2 parts: the response headers and the body. May 7, 2012 at 15:56
  • Personally I think has more to do with the fact that you Cannot modify header information after they've been set. In regular ASP.NET you would just buffer the response. May 7, 2012 at 15:57
  • I've decided to send the modified header information, accepting that I'll lose any error codes returned. Server exceptions are always returning a well defined JSON exception string, which I can parse to see if the service call failed.
    – John
    May 8, 2012 at 10:33

1 Answer 1

0

An option would be to throw a WebFaultException with a meaningful HTTP status and message. Example: throw new WebFaultException("Invalid request received.", HttpStatusCode.BadRequest);
BadReuqest code is 400.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.