【问题标题】:Catch JSON deserialization error in WCF service在 WCF 服务中捕获 JSON 反序列化错误
【发布时间】:2013-07-03 18:55:53
【问题描述】:

我有一个基本的 WCF 服务:

[OperationContract]
[WebInvoke(Method = "POST",
    ResponseFormat = WebMessageFormat.Json, 
    RequestFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "object/{id}")]
void MyMethod(String id, MyType myObject);

当我使用有效的 JSON 数据调用此服务时,它按预期工作。当我使用无效的 JSON 数据调用它时,我会收到请求错误,这也是意料之中的。

但是,此错误包含堆栈跟踪和一般消息。

我的问题是如何捕获这个错误并返回我自己的消息或 html 页面?

【问题讨论】:

    标签: c# json wcf rest


    【解决方案1】:

    您可以在 web.config 的 <system.web> 部分使用 <customErrors /> 和/或您可以在 Global.asax 上使用 Application_Error 事件:

    protected void Application_Error(object sender, EventArgs e)
    {
           // Your error handling stuff
           System.Web.HttpContext context = HttpContext.Current;
           System.Exception ex = context.Server.GetLastError();
    
           context.Server.ClearError();
    
           Response.Redirect("CustomError.aspx");
    }
    

    【讨论】:

    • 我的项目中没有 Global.asax。我尝试添加它,但它从未被调用。我也尝试过<customErrors /> 解决方案,但它永远不会重定向到新页面。
    • 您如何托管您的服务? IIS?自托管?
    • 两种解决方案都应该有效。粘贴 Global.asax 声明的代码,必须像这样开始: public class Global : System.Web.HttpApplication { ... }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多