有一个Request对象,获取请求内容类型很容易。但是如何为响应指定内容类型?我的控制器看起来像这样(为简洁起见,其他动作被删除):
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(); } }
Response.ContentType = "text/csv";
有一点研究表明,我们可以键入Action来返回一个HttpResponseMessage。所以我的方法的结尾将如下所示:
var response = new HttpResponseMessage() ; response.Headers.Add("ContentType","text/csv"); response.Content = //not sure how to set this return response;
关于HttpContent的文档是相当稀疏的,有人可以建议我如何将我的StringBuilder的内容变成一个HttpContent对象?
解决方法
您必须将方法的返回类型更改为HttpResponseMessage,然后使用Request.CreateResponse:
// GET api/Audit/CSV [HttpGet,ActionName("CSV")] public HttpResponseMessage Csv(Guid sessionId,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; }