本文介绍了如何指定的ContentType的Web API控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个请求对象,并获取请求的内容类型是很容易。但你如何指定的内容类型的响应?我的控制器看起来像这样(切除为简洁起见其他操作):

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";

一个小的研究表明,我们可以输入操作返回一个Htt的presponseMessage。所以我的方法的结尾是这样的:

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;

在HttpContent的文档是相当稀疏,任何人都可以告诉我如何得到我的StringBuilder的内容到HttpContent对象?

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

推荐答案

您必须对方法的返回类型更改为的Htt presponseMessage ,然后使用 Request.CreateResponse

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;
}

这篇关于如何指定的ContentType的Web API控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:24
查看更多