user793468
user793468

Reputation: 4966

How can I redirect/return an aspx page from a controller action?

How Can I return a particular aspx page wiht the path from a controller action?

Here is how I redirect from a controller action:

Response.Redirect("_PDFLoader.aspx?Path=" + FilePath  +  id + ".pdf");

Even tried the following:

return Redirect("_PDFLoader.aspx?Path=" + FilePath + id + ".pdf");

Here is my _PDFLOader.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="_PDFLoader.aspx.cs" Inherits="Proj._PDFLoader" %>

Here is my CodeBehind file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace Proj
{
    public partial class _PDFLoader : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string OutfilePath = Request.QueryString["Path"].ToString();
            FileStream objfilestream = new FileStream(OutfilePath, FileMode.Open, FileAccess.Read);
            int len = (int)objfilestream.Length;
            Byte[] documentcontents = new Byte[len];
            objfilestream.Read(documentcontents, 0, len);
            objfilestream.Close();

            if (File.Exists(OutfilePath)) File.Delete(OutfilePath);       

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", documentcontents.Length.ToString());
            Response.BinaryWrite(documentcontents);

        }
    }
}

Any help is much appreciated.

Upvotes: 0

Views: 5236

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The following should work:

public class SomeController: Controller
{
    public ActionResult SomeAction() 
    {
        return Redirect("~/_PDFLoader.aspx?Path=" + Url.Encode(FilePath + id) + ".pdf"");
    }
}

But from what I can see all that this _PDFLoader.aspx WebFrom does is to serve the file and then delete it. You could do this directly from your controller action:

public class SomeController: Controller
{
    public ActionResult SomeAction() 
    {
        string path = FilePath + id + ".pdf";
        if (!File.Exists(path))
        {
            return HttpNotFound();
        }
        byte[] pdf = System.IO.File.ReadAllBytes(path);
        System.IO.File.Delete(path);
        return File(pdf, "application/pdf", Path.GetFileName(path));
    }
}

and if you want the file to be displayed inline instead of downloading it:

return File(pdf, "application/pdf");

Upvotes: 4

Related Questions