Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 981
Peter Wone Avatar asked Apr 30 '14 06:04

Peter Wone


People also ask

How do we specify response data type while making the request to Web API?

Web API converts request data into CLR object and also serialize CLR object into response data based on Accept and Content-Type headers. Web API includes built-in support for JSON, XML, BSON, and form-urlencoded data. It means it automatically converts request/response data into these formats OOB (out-of the box).

How do I pass body parameters in Web API?

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.

How do I set content negotiation in Web API?

In Web API, content negotiation is performed by the runtime (at the server side) to determine the media type formatter to be used based to return the response for an incoming request from the client side. Content negotiation is centered on Media type and Media type formatter.


1 Answers

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;
}
like image 79
haim770 Avatar answered Oct 22 '22 15:10

haim770