Mar*_*kus 9 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 HttpException((int)HttpStatusCode.BadRequest, "Error Message");
}
Run Code Online (Sandbox Code Playgroud)
也:
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
这些都回应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
}
}
Run Code Online (Sandbox Code Playgroud)
基本上你不能,也就是说,当抛出异常时,结果将始终是相同的 500。
归档时间: |
|
查看次数: |
5349 次 |
最近记录: |