以下は、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"}]
前もって感謝します