0

I have the following code:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static MyResponse myMethod(ParameterClass parameters)
{
    MyResponse resp = new MyResponse();
    resp.errors.Add("Some error message");
    HttpContext.Current.Response.StatusCode = 400;
    return resp;
}

running this with jQuery.ajax using url MyPage.aspx/myMethod this call does not return my payload from MyResponse object. Once i switch the statuscode to 200 the return works using the success callback in ajax, but i want to return custom error messages with 4xx and 5xx status codes, how to make it work.

It looks like IIS is the problem, but what do i have to do to still allow returning my class objects on error?

Update 1: i also watched network tab in chrome, IIS is not returning the payload at all, so jQuery cannot be the problem.

Update 2: my jquery ajax call

$.ajax({
  url: 'MyPage.aspx/myMethod',
  data: JSON.stringify({ parameters: request }),
  dataType: "json",
  type: "POST",
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    ...
  },
  error: function (data) {
    // data.responseJSON is undefined and data.responseText contains only HTTP status code text, like "Bad Request" when code was 400.
  }
});
NovumCoder
  • 4,349
  • 9
  • 43
  • 58

1 Answers1

0

Ok found it in another stackoverflow post.

The solution was to add the following to web.config:

<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
  <clear/>
</httpErrors>

By default IIS is replacing the response on error, here the attribute "existingResponse=PassThrough" is the key. Now responseJSON and responseText is filled with my custom content returned by the webmethod.

Found in HttpResponseMessage content lost when HTTP Status is Bad Request

NovumCoder
  • 4,349
  • 9
  • 43
  • 58