Return status code 404 with JSON data for ASP WebMethod

Viewed 1477

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.

1 Answers
Related