4

I'm trying to return status code 404 with a JSON response, like such:

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static dynamic Save(int Id)
{
    HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;
    return new 
    {
        message = $"Couldn't find object with Id: {id}"
    };
}

But I keep getting HTML error page for 404 error instead of the JSON response. I've tried various of manipulating the Response with Flush, Clear, Write, SuppressContent, CompleteRequest (Not in order), but whenever I return 404 it still picks up the html error page.

Any ideas on how I can return a status code other than 200 OK (Since it's not ok, it's an error) and a JSON response?

I know I can throw an exception, but I'd prefer not to since it doesn't work with customErrors mode="On"

This is an older Website project in ASP.Net, and it seems most solutions in ASP MVC doesn't work.

9
  • if it's an error why not go for an InternalServerException. if it's an invallid parameter as in {id} why not go for a BadRequest. When using System.Web.Http.ApiController it's especially easy you can just: return InternalServerError(Exception) or return BadRequest(string) Commented Nov 20, 2017 at 10:14
  • Did you try to write into HttpContext.Current.Response.OutputStream ? Or into HttpContext.Current.Response.Output (Output here is a TextWriter) Commented Nov 20, 2017 at 10:17
  • Just finished testing something else: In case you want to return a HttpResponseMessage use: return Request.CreateResponse(HttpStatusCode.NotFound, "My message"); Commented Nov 20, 2017 at 10:27
  • @Drag0nvil It's not an invalid parameter if it's an int, is it? My reasoning is that if I couldn't find an object (in the DB for example) with the Id supplied, it's an Object Not Found error. And return InternalServerError(Exception) doesn't work with this version of ASP WebSites sadly. And returning the HTTP status code for Internal Server Error will have the same effect as 404, it gives me a HTML page. Returning the status code for Bad Request only returns a text response "Bad request" and nothing else, so that sadly doesn't work either. Commented Nov 20, 2017 at 10:30
  • See my second post, when I used that on my REST server and tested it with postmen it would show the: "My message" in the body. if not then I'm sorry but your version/configuration is different the one I'm using. Commented Nov 20, 2017 at 10:32

1 Answer 1

7
+100

Usually when you get he HTML error page that is IIS taking over the handling of the not found error.

You can usually bypass/disable this by telling the response to skip IIS custom errors.

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static dynamic Save(int id) {
    //...

    //if we get this far return not found.
    return NotFound($"Couldn't find object with Id: {id}");
}

private static object NotFound(string message) {
    var statusCode = (int)System.Net.HttpStatusCode.NotFound;
    var response = HttpContext.Current.Response;
    response.StatusCode = statusCode;
    response.TrySkipIisCustomErrors = true; //<--
    return new {
        message = message
    };
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're a lifesaver Nkosi, it worked perfectly! Skipping the custom errors only for these webmethods is not an issue since I don't see the purpose of having HTML errors as response to an AJAX request.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.