5
votes

I have implemented a custom media formatter and it works great when the client specifically requests "csv" format.

I have tested my api controller with this code:

        HttpClient client = new HttpClient();
        // Add the Accept header
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));

However, when I open the same URL from a web browser it returns JSON not CSV. This is probably due to standard ASP.NET WebAPI configuration that sets JSON as the default media formatter unless otherwise specified by the caller. I want this default behavior on every other web service I have but NOT on this single operation that returns CSV. I want the default media handler to be the CSV handler that I implemented. How do I configure the Controller's endpoint such that it returns CSV by default and only returns JSON/XML if requested by the client?

1

1 Answers

0
votes

Which version of Web API are you using?

If you are using 5.0 version, you could use the new IHttpActionResult based logic like below:

public IHttpActionResult Get()
{
    MyData someData = new MyData();

    // creating a new list here as I would like CSVFormatter to come first. This way the DefaultContentNegotiator
    // will behave as before where it can consider CSVFormatter to be the default one.
    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    return new NegotiatedContentResult<MyData>(HttpStatusCode.OK, someData,
                    Configuration.Services.GetContentNegotiator(), Request, respFormatters);
}

If you are using 4.0 version of Web API, then you could the following:

public HttpResponseMessage Get()
{
    MyData someData = new MyData();

    HttpResponseMessage response = new HttpResponseMessage();

    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
    ContentNegotiationResult negotiationResult = negotiator.Negotiate(typeof(MyData), Request, respFormatters);

    if (negotiationResult.Formatter == null)
    {
        response.StatusCode = HttpStatusCode.NotAcceptable;
        return response;
    }

    response.Content = new ObjectContent<MyData>(someData, negotiationResult.Formatter, negotiationResult.MediaType);

    return response;
}