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.
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.