gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:50:51 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com