简体   繁体   中英

Return status code 404 with JSON data for ASP WebMethod

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.

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
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM