【问题标题】:Handle WebFaultException to display error message on label处理 WebFaultException 以在标签上显示错误消息
【发布时间】:2012-04-19 11:34:06
【问题描述】:

在我的 WCF REST 服务中,有一个方法 GetUser(username),它将

throw new WebFaultException<string>("there is no this user", HttpStatusCode.NotFound);

在我的 asp.net 客户端中,我想捕获上述异常并在标签上显示“没有此用户”。但是当我尝试如下编码时:

MyServiceClient client = new MyServiceClient;
try
{
    client.GetUser(username);
}
catch (Exception ex)
{
    Label.Text = ex.Message;
}

结果显示消息“未找到”而不是“没有此用户”。

如何显示“没有此用户”的消息?


20/4
在我的 REST 服务中:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "{username}")]
void GetUser(username);

.svc 类:

 public void GetUser(username)
    {
        try
        {
            Membership.GetUser(username);
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            throw new WebFaultException<string>("there is no this user", HttpStatusCode.NotFound);
        }
    }

【问题讨论】:

    标签: asp.net wcf rest


    【解决方案1】:

    如果您查看文档,很明显您应该显示Detail,而不是Message。你的行应该是:

    MyServiceClient client = new MyServiceClient;
    try
    {
        client.GetUser(username);
    }
    catch (FaultException<string> ex)
    {
        var webFaultException = ex as WebFaultException<string>;
        if (webFaultException == null)
        {
           // this shouldn't happen, so bubble-up the error (or wrap it in another exception so you know that it's explicitly failed here.
           rethrow;
        }
        else
        {
          Label.Text = webFaultException.Detail;
        }
    }
    

    编辑:更改异常类型

    此外,您应该捕获您感兴趣的特定异常 (WebFaultException&lt;string&gt;),而不是碰巧抛出的任何旧异常。特别是,DetailWebFaultException&lt;string&gt; 类型上只有 Detail,它不在 Exception 上。

    WebFaultException Class

    【讨论】:

    • 但是当我将 Exception 更改为 WebFaultException 时,它无法到达 catch{},它会在“client.GetUser(username);”中引发异常它显示“用户代码未处理FaultException”
    • 您是否尝试将WebFaultException&lt;string&gt; 更改为FaultException&lt;string&gt;。从您所说的看来,实际抛出的异常类型是FaultException,而您想要WebFaultException,我已经更新了代码以反映这一点。有用吗?
    • 不起作用,虽然可以到达catch{},webFaultException为null,无法显示错误信息。
    • 好吧,再看看这个问题,如果你打算拥有一个 REST 服务,你根本不应该使用 FaultExceptions,它们用于基于 SOAP 的 WCF 服务,它们是 完全不同。您是否为 REST 服务使用任何框架?您如何将其定义为 REST?
    • 我只是使用vs2010来创建它。我已经发布了我的服务代码,请查看我编辑的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多