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?
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).
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With