在响应
@L_502_0@的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"); }
也:
[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(); throw ex; } }
这些都回应500.
非常感谢.
解决方法
将您的代码更改为:
[WebMethod] [ScriptMethod(UseHttpGet = true,"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.