【问题标题】:MVC WebApi. Want to get format of HttpResponseMessage according to current formatterMVC WebAPI。想根据当前的格式化程序获取 HttpResponseMessage 的格式
【发布时间】:2012-06-20 20:44:47
【问题描述】:

下面是我的 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"}]

提前致谢

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您返回的是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 接受的客户端会看到:

    {"Message":"Sorry! no Employee found with id 78"}
    

    【讨论】:

    • 卡住是什么意思?有什么问题?
    • 对不起,我按下了回车键,这发布了我不完整的消息。实际上我想问我是否被过滤器(ActionFilterAttribute)的 OnActionExecuting 事件困住了。公共覆盖无效 OnActionExecuting(HttpActionContext context) { context.Response = ? (如何从这里发送错误消息,就像我们从 Get 方法中一样)}
    • 我在这里找到了解决方案:stackoverflow.com/questions/11189161/…
    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 2021-04-03
    相关资源
    最近更新 更多