asp.net-mvc-4asp.net-web-api

How to specify ContentType for Web API controller method


There's a Request object, and getting the request content type is easy. But how do you specify a content type for the response? My controller looks like this (other actions excised for brevity):

public class AuditController : ApiController
{   
  // GET api/Audit/CSV
  [HttpGet, ActionName("CSV")]
  public string Csv(Guid sessionId, DateTime a, DateTime b, string predicate)
  {
    var result = new StringBuilder();
    //build a string
    return result.ToString();
  }
}

This works fine except that it has the wrong content type. I'd like to do this

Response.ContentType = "text/csv";

A little research reveals that we can type the Action to return an HttpResponseMessage. So the end of my method would look like this:

  var response = new HttpResponseMessage() ;
  response.Headers.Add("ContentType","text/csv");
  response.Content = //not sure how to set this
  return response;

The documentation on HttpContent is rather sparse, can anyone advise me on how to get the contents of my StringBuilder into an HttpContent object?


Solution

  • You'll have to change the return type of the method to HttpResponseMessage, then use Request.CreateResponse:

    // GET api/Audit/CSV
    [HttpGet, ActionName("CSV")]
    public HttpResponseMessage Csv(Guid sessionId, DateTime a, DateTime b, string predicate)
    {
        var result = new StringBuilder();
    
        //build a string
    
        var res = Request.CreateResponse(HttpStatusCode.OK);
        res.Content = new StringContent(result.ToString(), Encoding.UTF8, "text/csv");
    
        return res;
    }