2012-04-19 10 views
0

にエラーメッセージを表示するように、そこにあるハンドルWebFaultExceptionは私のWCFのRESTサービスでラベル

私のasp.netクライアントで
throw new WebFaultException<string>("there is no this user", HttpStatusCode.NotFound); 

、私は例外とショーの上にキャッチしたいと思うでしょう方法GETUSER(ユーザー名)、ラベルに「このユーザーはありません」と表示されます。私は次のようにコーディングしようとすると、しかし:

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

それは結局のところ、「このユーザーが何にあり」の代わりにメッセージを表示しない「NOTFOUND」。

「このユーザーはいません」というメッセージを表示するにはどうすればよいですか?

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

.SVCクラス::私のRESTサービスで

4分の20


は、あなたがすべきことを

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

あなたがドキュメントに見れば、それは明らかですMessageではなく、Detailが表示されます。あなたの行は次のようになります。

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

EDIT:また、あなたはあなたが興味のあることを特定の例外(WebFaultException<string>)、ないに起こるすべての古い例外をキャッチする必要があります

例外タイプを変更しましたスローされる。特に、はWebFaultException<string>タイプにしかないため、Exceptionにはありません。

WebFaultException Class

+0

を参照してくださいしかし、私はWebFaultException に例外を変更すると、それは} {キャッチに達することができない、それが中に例外をスロー「client.GetUser(ユーザー名);」 「FaultExceptionがユーザコードで処理されていませんでした。」 –

+0

'WebFaultException 'を 'FaultException 'に変更しようとしましたか?実際に発生する例外の型が 'FaultException'で、' WebFaultException'が必要な場合は、これを反映するようにコードを更新したようです。それは動作しますか? – nicodemus13

+0

は動作しませんが、catch {}に達する可能性がありますが、webFaultExceptionはnullです。エラーメッセージを表示できません。 –

関連する問題