使用ASP WebMethod

时间:2017-11-20 10:09:05

标签: 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响应。我已经尝试了各种操作Response与Flush,Clear,Write,SuppressContent,CompleteRequest(不按顺序),但每当我返回404时它仍然会选择html错误页面。

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

我知道我可以抛出异常,但我不愿意,因为它不适用于customErrors mode="On"

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

1 个答案:

答案 0 :(得分:3)

通常当你得到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
    };
}