Skip to main content
 首页 » 编程设计

c#之为 ASP WebMethod 返回带有 JSON 数据的状态代码 404

2024年02月27日37cmt

我正在尝试使用 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}" 
    }; 
} 

但我一直收到 404 错误的 HTML 错误页面,而不是 JSON 响应。我尝试了各种使用 Flush、Clear、Write、SuppressContent、CompleteRequest 来操作 Response 的方法(不按顺序),但每当我返回 404 时,它仍然会显示 html 错误页面。

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

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

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

请您参考如下方法:

通常当您收到 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 
    }; 
}