问题
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();
}
}
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.
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.
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.
回答1:
Ah, this was a stupid issue. The exception information only appears if you have:
<customErrors mode="Off" />
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.
Update:
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.
回答2:
The exception types are not serializable. Use FaultException instead.
throw new FaultException(..);
来源:https://stackoverflow.com/questions/13546429/how-to-get-exception-information-when-calling-json-web-service