Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return status code 404 with JSON data for ASP WebMethod

Tags:

c#

asp.net

iis

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.

like image 224
Joakim Johansson Avatar asked Oct 28 '25 12:10

Joakim Johansson


1 Answers

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
    };
}
like image 91
Nkosi Avatar answered Oct 30 '25 02:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!