如何调用JSON Web服务时获得异常信息异常、信息、JSON、Web

2023-09-05 04:16:31 作者:心再给我霸占一次

在.NET 3.5中,我有以下code:

In .NET 3.5, I had the following code:

[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();
   }
}

当我称呼它,如果我通过一个无效的用户名和密码后, InvalidUsernameOrPasswordException 将会被抛出,我可以通过查看 error.get_exceptionType()。这是因为Web服务将序列化JSON的异常信息。

When I would call it, if I passed in an invalid username and password, the InvalidUsernameOrPasswordException would be thrown and I could catch the exception in Javascript by looking at error.get_exceptionType(). This is because the web service would serialize the exception info in JSON.

但是,一旦我升级到.NET 4.5,这打破了。现在,当我传递一个无效的用户名和密码,我得到的HTTP响应:

However, once I upgraded to .NET 4.5, this broke. Now, when I pass in an invalid username and password, I get the HTTP response:

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":""}

基本上,异常类型丢失,替​​换为一般性错误消息。

Basically, the exception type is lost and replaced with a generic error message.

是什么造成了这种行为改变,而且是有还是有办法返回异常信息的JSON? pretty的很多我的整个设计的API是依赖于这种行为。

What caused this behavior to change, and is there still a way to return exception information in JSON? Pretty much my entire API is designed to rely on this behavior.

推荐答案

嗯,这是一个愚蠢的问题。异常信息只有当你有出现:

Ah, this was a stupid issue. The exception information only appears if you have:

<customErrors mode="Off" />

在你的web.config(下&LT;的System.Web&GT; )。实际上,我不知道这是一个.NET 3.5 - > .NET 4.5行为的改变,或者如果它打破了,当我重新写我的web.config生成过程中使用的web.config转换

In your web.config (under <system.web>). I'm actually not sure if this is a .NET 3.5 -> .NET 4.5 change in behavior, or if it got broke when I was re-writing my web.config build process using web.config transforms.

有谁知道,如果有一种方法来对每个网络服务水平的控制呢?我宁愿不显示在正常的页面请求完整的调试信息。

Does anyone know if there's a way to control this on a per web-service level? I'd rather not show full debug info on normal page requests.

更新:

我也来了抛出异常,从一个Web服务进行通信的错误信息得出的结论是真的不是一个好的设计。事实上,我写了关于这个问题的一个职位上我的博客那些有兴趣。

I also came to the conclusion that throwing exceptions to communicate error information from a web service is really not a good design. In fact, I wrote a post on the subject on my blog for those interested.

 
精彩推荐
图片推荐