更改Web API响应格式化程序

时间:2013-06-04 18:00:34

标签: c# asp.net jquery asp.net-web-api mediatypeformatter

我在SelfHost配置上有一个APIController,它可以生成像XML Documents这样的响应:

public XmlDocument Get(int id)
{
    XmlDocument doc;
    doc = repo.get(id); // simplified

    if(doc != null)
        return doc;

    throw new HttpResponseExeption(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Something went terribly wrong."));
}

如果出现异常,我想以JSON格式向客户端发回响应,而不是XML, 所以我可以在jquery AJAX请求中错误地解析错误消息(错误回调):

JSON.parse(jqXHR.responseText).Message;

如果jQuery请求为正确的流发送一个dataType:'xml',我怎样才能将HttpResponseException的格式化“动态”更改为JSON?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您似乎总是希望将错误发送回JSON而不是内容协商为XML?这似乎很奇怪,因为如果客户端要求XML中的响应主体,他们通常也希望以XML格式发回错误消息。

但如果你真的必须这样做,那就是你要做的事情:

public XmlDocument Get(int id)
{
    XmlDocument doc;
    doc = repo.get(id); // simplified

    if(doc != null)
        return doc;

    throw new HttpResponseExeption(
        Request.CreateResponse(HttpStatusCode.NotFound, new HttpError("Something went terribly wrong."), Configuration.Formatters.JsonFormatter));
}