C# 调用JSON web服务时如何获取异常信息
在.NET 3.5中,我有以下代码:C# 调用JSON web服务时如何获取异常信息,c#,asp.net,.net,web-services,asp.net-ajax,C#,Asp.net,.net,Web Services,Asp.net Ajax,在.NET 3.5中,我有以下代码: [WebService(Namespace = "http://kitchenpc.com/schemas/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class KitchenPC : System.Web.Services.WebService { [WebMethod] public LogonResult
[WebService(Namespace = "http://kitchenpc.com/schemas/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class KitchenPC : System.Web.Services.WebService
{
[WebMethod]
public LogonResult Logon(string username, string password)
{
//If username and password are not valid...
throw new InvalidUsernameOrPasswordException();
}
}
当我调用它时,如果我传入一个无效的用户名和密码,就会抛出invalidUserName或PasswordException
,我可以通过查看error.get\u exceptionType()
在Javascript中捕获异常。这是因为web服务将在JSON中序列化异常信息
然而,一旦我升级到.NET4.5,它就崩溃了。现在,当我传入无效的用户名和密码时,我会得到HTTP响应:
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
jsonerror: true
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 24 Nov 2012 22:42:33 GMT
Content-Length: 91
{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
基本上,异常类型将丢失并替换为一般错误消息
是什么导致了这种行为的改变,还有没有办法用JSON返回异常信息?我的整个API几乎都是基于这种行为设计的。异常类型是不可序列化的。改用FaultException
throw new FaultException(..);
啊,这是一个愚蠢的问题。只有在以下情况下,才会显示异常信息:
<customErrors mode="Off" />
在web.config中(在
下)。实际上,我不确定这是否是.NET 3.5->.NET 4.5的行为变化,或者在我使用web.config转换重新编写web.config构建过程时它是否被破坏
有人知道有没有办法在每个web服务级别上控制这一点吗?我不希望在正常页面请求上显示完整的调试信息
更新:
我还得出结论,抛出异常以从web服务传递错误信息确实不是一个好的设计。事实上,我在博客上为那些感兴趣的人写了一篇文章。True。对不起,我没有注意到这些不是WCFs。:)是的,总有一天我需要切换到WCF。。它更强大。不过我现在需要把这个修好。