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

标签 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}"
    };
}

但我一直收到 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
    };
}

关于c# - 为 ASP WebMethod 返回带有 JSON 数据的状态代码 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47389498/

相关文章:

c# - 我如何遍历 PropertyCollection

asp.net - IIS 应用程序 - 一些 Urls 应该需要客户端 ssl 证书,而其他的则不需要

c# - Linq 选择在内存中执行的不同计数

c# - 将连接字符串放在 applicationSettings 中有什么问题吗?

c# - ASP.Net 5 AuthorizationHandler 失败重定向

c# - Entity Framework 连接字符串

c# - Entity Framework 存储过程返回空对象

C#调用基类构造函数

c# - 如何比较两个无序列表框之间的项目

asp.net - 从 ASP .Net Web 服务访问 MSMQ 时出现权限错误