0

在我的 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;
}

结果显示消息“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);
        }
    }
4

1 回答 1

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>您感兴趣的特定异常 ( ),而不是碰巧抛出的任何旧异常。特别是,因为你只有DetailonWebFaultException<string>类型,它不是 on Exception

请参阅WebFaultException 类

于 2012-04-19T11:50:21.210 回答