Asp.net 我可以设置HTTP响应代码吗&;在ASMX JSON服务上引发异常?

Asp.net 我可以设置HTTP响应代码吗&;在ASMX JSON服务上引发异常?,asp.net,error-handling,asmx,http-status-codes,webmethod,Asp.net,Error Handling,Asmx,Http Status Codes,Webmethod,在响应JSON的ASP.NET ASMX WebMethod中,我可以抛出异常并设置HTTP响应代码吗?我认为如果我抛出一个HttpException,状态代码将被适当地设置,但是它不能让服务响应500错误以外的任何东西 我尝试了以下方法: [WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public void TestWebMethod() { throw new H

在响应JSON的ASP.NET ASMX WebMethod中,我可以抛出异常并设置HTTP响应代码吗?我认为如果我抛出一个HttpException,状态代码将被适当地设置,但是它不能让服务响应500错误以外的任何东西

我尝试了以下方法:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
}
此外:

这两个国家的回复都是500


非常感谢。

将您的代码更改为:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    try {
        throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
    }
    catch ( HttpException ex ) {
        Context.Response.StatusCode = ex.GetHttpCode();

        // See Markus comment
        // Context.Response.StatusDescription("Error Message");
        // Context.Response.StatusDescription(ex.Message); // exception message
        // Context.Response.StatusDescription(ex.ToString()); // full exception
    }
}

基本上你不能,也就是说,当抛出一个异常时,结果总是相同的500。

你有什么进展吗?这会导致相反的问题。例外情况永远不会出现在响应中。客户端有状态代码,但没有错误消息。为什么Response.StatusDescription(例如ToString())不能同时有这两个代码?刚刚更新了我的答案。StatusDescription应该镜像StatusCode(200为OK,404为Not Found,等等)。它不应该是一个自定义值。@Markus,我同意,但对于实际的500或任何其他不太常见的错误,自定义描述可能会有用。
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void TestWebMethod() {
    try {
        throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message");
    }
    catch ( HttpException ex ) {
        Context.Response.StatusCode = ex.GetHttpCode();

        // See Markus comment
        // Context.Response.StatusDescription("Error Message");
        // Context.Response.StatusDescription(ex.Message); // exception message
        // Context.Response.StatusDescription(ex.ToString()); // full exception
    }
}