2

以下は、MVC Web Api RC の Get メソッドです。

public Employee Get(int id)
{
     Employee emp= null;

     //try getting the Employee with given id, if not found, gracefully return error message with notfound status
     if (!_repository.TryGet(id, out emp))
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
         {
             Content = new StringContent("Sorry! no Employee found with id " + id),
             ReasonPhrase = "Error"
         });

      return emp;
}

ここでの問題は、エラーがスローされるたびに、「申し訳ありませんが、ID を持つ従業員が見つかりませんでした」がプレーンテキスト形式になっていることです。ただし、現在のフォーマッターに従ってフォーマットを設定したかったのです。デフォルトのように、global.asax に XML フォーマッターを設定しました。したがって、エラーは XML 形式で表示されます。何かのようなもの :

<error>
  <error>Sorry! no Employee found with id </error>
</error>

Json フォーマッタについても同様です。そのはず :

[{"errror","Sorry! no Employee found with id"}]

前もって感謝します

4

1 に答える 1

7

を返していStringContentます。これは、コンテンツがそのまま返されることを意味し、それをフォーマットするのはあなた次第です。

個人的に私はモデルを定義します:

public class Error
{
    public string Message { get; set; }
}

その後:

if (!_repository.TryGet(id, out emp))
{
    var response = Request.CreateResponse(
        HttpStatusCode.NotFound,
        new Error { Message = "Sorry! no Employee found with id " + id }
    );
    throw new HttpResponseException(response);
}

XML Accept が有効なクライアントには、次のように表示されます。

<Error xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AppName.Models">
    <Message>Sorry! no Employee found with id 78</Message>
</Error>

JSON Accept が有効なクライアントには、次のように表示されます。

{"Message":"Sorry! no Employee found with id 78"}
于 2012-06-20T11:42:58.353 に答える