处理WebFaultException以在标签上显示错误消息

时间:2012-04-19 11:34:07

标签: asp.net wcf rest

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

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;
}

结果显示消息“NotFound”而不是“没有这个用户”。

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


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

1 个答案:

答案 0 :(得分:0)

如果您查看文档,很明显您应该展示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<string>),而不是任何恰好抛出的旧异常。特别是,因为Detail类型上只有WebFaultException<string>,所以它不在Exception上。

请参阅WebFaultException Class