使用 ASP WebMethod 的 JSON 数据返回状态代码 404

Joa*_*son 3 c# asp.net iis

我正在尝试使用 JSON 响应返回状态代码 404,如下所示:

[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}"
    };
}
Run Code Online (Sandbox Code Playgroud)

但是我不断收到 404 错误的 HTML 错误页面,而不是 JSON 响应。我尝试了各种操作ResponseFlush、Clear、Write、SuppressContent、CompleteRequest(不按顺序),但是每当我返回 404 时,它仍然会选择 html 错误页面。

关于如何返回 200 OK 以外的状态代码(因为它不正常,这是一个错误)和 JSON 响应的任何想法?

我知道我可以抛出异常,但我不想这样做,因为它不起作用 customErrors mode="On"

这是 ASP.Net 中的一个较旧的网站项目,似乎 ASP MVC 中的大多数解决方案都不起作用。

Nko*_*osi 5

通常,当您获得 HTML 错误页面时,IIS 会接管对未找到错误的处理。

您通常可以通过告诉响应跳过 IIS 自定义错误来绕过/禁用此功能。

[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
    };
}
Run Code Online (Sandbox Code Playgroud)