Search code examples
c#asp.netjqueryasp.net-web-apimediatypeformatter

Change Web API Response Formatter


I've an APIController on SelfHost Configuration that generates responses like 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."));
}

In case of exception i wanna send back to client a response in JSON format and not XML, so I can correctly parse the error message in a jquery AJAX request (error callback):

JSON.parse(jqXHR.responseText).Message;

How can I change the formatter of HttpResponseException "on the fly" to be JSON, considering that jQuery request send a dataType: 'xml' for the correct flow?


Solution

  • If I'm understanding correctly, it seems like you always want the error to be sent back in JSON instead of content-negotiated as XML? This seems strange since if a client is asking for a response body in XML, they typically want error messages to be sent back in XML as well.

    But if you really must, here's how you'd go about doing it:

    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));
    }