[英]ASP.Net MVC: Exporting the results of an ApiController action
In my application I have a few grids that each get their data source from an ApiController
action. 在我的应用程序中,我有一些网格,每个网格都从
ApiController
动作获取其数据源。 I want to add an option for the user to export these grid into either CSV, PDF, Excel, etc. Writing code to convert the datasource to the expected format is not problem. 我想为用户添加一个选项,以将这些网格导出为CSV,PDF,Excel等。编写代码以将数据源转换为预期格式不是问题。 The problem is that I want to write re-usable code.
问题是我想编写可重用的代码。 Currently I have a separate action for each grid.
目前,我对每个网格都有单独的操作。
I could very easily add a new Export controller with matching actions that call into the same logic as the ApiController
, but that means if I have five ApiController
actions I will need five additional Controller
actions. 我可以很容易地添加一个具有匹配动作的新Export控制器,这些动作调用与
ApiController
相同的逻辑,但这意味着,如果我有五个ApiController
动作,我将需要五个附加Controller
动作。
What i'm wondering if if there was a way I could make a single export Controller
action, but somehow pass the details for the ApiController
to it. 我想知道是否有一种方法可以执行单个export
Controller
动作,但是以某种方式将ApiController
的详细信息ApiController
给它。
Any suggestions? 有什么建议么?
Here is what I found: 这是我发现的:
Instead of returning StreamContent
as the Content, I can make it work with ByteArrayContent
. 我可以使它与
ByteArrayContent
工作,而不是返回StreamContent
作为Content。
[HttpGet]
public HttpResponseMessage Generate()
{
var stream = new MemoryStream();
// processing the stream.
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "CertificationCard.pdf"
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.