6

次のコードを使用して、フィルター (ActionFilterAttribute) からクライアントにエラー メッセージを送信しています。

catch (Exception)
 {
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
    response.Content = new StringContent("User with api key is not valid");
    context.Response = response;
 }

しかし問題は、プレーンテキストでしか送信されないことです。現在のフォーマッタのフォーマットとして送信したかったのです。json または xml の形式のように。

ここで、これは StringContent() を使用しているためであることを知っています。しかし、カスタム Error オブジェクトを使用してどのように記述できるでしょうか? 同様に、以下も機能していません。

response.Content = new Error({Message = "User with api key is not valid"});

このためのコードをどのように書くのでしょうか? 前もって感謝します。

4

1 に答える 1

8

ええ、私は正しい書き方を見つけました。次のように書くことができます。

catch (Exception)
{
    var response = context.Request.CreateResponse(HttpStatusCode.NotFound, 
                        new Error { Message = "User with api key is not valid"});
    context.Response = response; 
}
于 2012-06-27T13:07:39.507 に答える