繁体   English   中英

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

[英]Return status code 404 with JSON data for ASP WebMethod

我正在尝试使用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响应。 我已经尝试了各种操作Response与刷新,清除,写入,SuppressContent,CompleteRequest(不按顺序),但每当我返回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
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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