有一个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, 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句