2012-04-19 54 views
0

在我的WCF REST服务上的错误消息,有一个方法的getUser(用户名),这将手柄WebFaultException显示标签

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

回答

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>)被抛出。特别是,因为WebFaultException<string>类型上只有Detail,所以它不在Exception上。

参见WebFaultException Class

+0

但是当我改变例外WebFaultException ,它不能达到捕获{},它扔在一个异常“client.GetUser(用户名);”它显示“FaultException未被用户代码处理” – 2012-04-19 12:31:31

+0

您是否尝试将'WebFaultException '更改为'FaultException '。从您所说的抛出异常的实际类型看来,似乎是一个'FaultException',并且您想要一个'WebFaultException',我已经更新了代码以反映这一点。它工作吗? – nicodemus13 2012-04-19 13:16:44

+0

不起作用,虽然它可以达到catch {},但webFaultException为null,不能显示错误消息。 – 2012-04-19 13:31:31