2

I want to be able to do something like this

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(object model)
    {
        if (model.OptionType == "Download")
        {
            var fileData = _service.GetPdf();
            if (fileData == null)
            {
                ModelState.AddModelError("", ValidationMessages.Get(ValidationMessages.Codes.SystemError));
                return View(model);
            }
            return File(fileData, "application/pdf", "file.pdf");
        }
        return View(model);
    }

However sitecore is complaining that OutputStream is not available when a custom TextWriter is used. I've seen this solution but if I do a RedirectToAction then I can't set the error as a ModelState error.

5
  • 3
    I'm voting to close this question as off-topic because it has nothing to do with Sitecore.
    – josedbaez
    Mar 21, 2017 at 9:37
  • 1
    The above code would work in a non-sitecore environment, hence it has everything to do with sitecore. Mar 21, 2017 at 22:54
  • You seem to already have the solution. Why can't you place the RedirectToAction call where you currently return File()?
    – Mark Cassidy
    Mar 27, 2017 at 7:10
  • Indeed, I've gone with that solution and to help the performance I'm adding the pdf to the session and reading it back again since _service.GetPdf() takes a while to generate the PDF. May 10, 2017 at 0:02
  • I'm voting to close this question as off-topic because resolved by OP/question no longer relevant.
    – Mark Cassidy
    Jul 24, 2017 at 13:03

1 Answer 1

0

You can wrap your filestream in a HttpResponseMessage:

[HttpPost]
public IHttpActionResult Index(object model)
{
    if (model.OptionType == "Download")
    {
        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StreamContent(PDFSTREAM);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.pdf"
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        return ResponseMessage(response);
    }
    return View(model);
}
2
  • Is IHttpActionResult in System.Web.Http? It's saying HttpRequestBase doesn't contain a definition for CreateResponse. Mar 21, 2017 at 23:00
  • Sorry, my answer is based on ApiController, I see now that it is not usable in this context.
    – Kasper
    Mar 22, 2017 at 6:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.