[英]How to pass and read a bitearray from ActionResult to Another using MVC4 C#
I was given a requirement to pass a MemoryStream from one ActionResult to another. 我被要求从一个ActionResult传递MemoryStream到另一个ActionResult。 In order to do this I am trying to pass a byte array from one action result to another action result, here's my code. 为了做到这一点,我试图将一个动作结果的字节数组传递给另一个动作结果,这是我的代码。
private MemoryStream GetSamplePdf(string name)
{
var ms = new MemoryStream();
using (var doc = new Document(PageSize.A4))
{
using (var writer = PdfWriter.GetInstance(doc, ms))
{
writer.CloseStream = false;
doc.Open();
doc.Add(new Paragraph(name));
doc.Close();
}
}
return ms;
}
public ActionResult PdfSpider()
{
var elem1 = PdfA();
var elem2 = PdfB();
return new EmptyResult();
}
public ActionResult PdfA()
{
var Pdfa = GetSamplePdf("A");
return Json(Pdfa.GetBuffer(), JsonRequestBehavior.AllowGet);
}
public ActionResult PdfB()
{
var Pdfb = GetSamplePdf("B");
return Json(Pdfb.GetBuffer(), JsonRequestBehavior.AllowGet);
}
How may I read the values returned from Pdfa and Pdfb and construct individual memory streams inside the spider action result? 如何读取从Pdfa和Pdfb返回的值,并在Spider动作结果内部构造各个内存流?
The Json
method returns a JsonResult
, which in turn has a Data
property containing the byte buffer. Json
方法返回一个JsonResult
,而JsonResult
具有一个包含字节缓冲区的Data
属性。
So, inside PdfSpider
you can cast back the ActionResult
to JsonResult
, get the Byte buffer from Data
and reconstruct a MemoryStream
: 因此,在PdfSpider
内部,您可以将ActionResult
退回给JsonResult
,从Data
获取Byte缓冲区并重建MemoryStream
:
var bytebufferA = (byte[])((JsonResult)PdfA()).Data;
var bytebufferB = (byte[])((JsonResult)PdfB()).Data;
var streamA = new MemoryStream(bytebufferA);
var streamB = new MemoryStream(bytebufferB);
A better solution would be (imo) to write internal functions GetStreamA()
and GetStreamB()
and use them by both PdfA()
/ PdfB()
and PdfSpider
like 更好的解决方案是(imo)编写内部函数GetStreamA()
和GetStreamB()
,并像PdfA()
/ PdfB()
和PdfSpider
一样使用它们
private MemoryStream GetStreamA() {
return GetSamplePdf("A");
}
public ActionResult PdfA() {
return Json(GetStreamA().GetBuffer(), JsonRequestBehavior.AllowGet);
}
// ...
// Same for PdfB()/GetStreamB()
// ...
public ActionResult PdfSpider() {
var streamA = GetStreamA();
var streamB = GetStreamB();
// ...
}
(This is what @bgs264 meant in his comment, I think ...) (我想这就是@ bgs264在他的评论中的意思……)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.