MVC WebApi.想要根据当前的格式化程序获取HttpResponseMessage的格式

Sac*_*mar 2 asp.net-mvc-4 asp.net-web-api

下面是我的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;
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是,无论何时抛出错误"抱歉!没有找到带有id的员工",只是采用平面文本格式.但是我想根据我当前的格式化程序设置格式.就像默认情况下我在global.asax中设置了XML格式化程序.因此错误应以XML格式显示.就像是 :

<error>
  <error>Sorry! no Employee found with id </error>
</error>
Run Code Online (Sandbox Code Playgroud)

同样适用于Json格式化程序.它应该是 :

[{"errror","Sorry! no Employee found with id"}]
Run Code Online (Sandbox Code Playgroud)

提前致谢

Dar*_*rov 7

你回来了StringContent.这意味着内容将按原样返回,由您来格式化.

我个人会定义一个模型:

public class Error
{
    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

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);
}
Run Code Online (Sandbox Code Playgroud)

然后,启用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>
Run Code Online (Sandbox Code Playgroud)

和启用JSON接受的客户端将看到:

{"Message":"Sorry! no Employee found with id 78"}
Run Code Online (Sandbox Code Playgroud)