Robin Purbia
Robin Purbia

Reputation: 227

HTTP Request and Response C#

I am working on Server side project in C# which receives request from various terminals to download a particular file. For this, on Server side I am creating a web application to process HTTP Request from clients. How to send a File (in Bytes) as Response??

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //get parameters
            string str = Request.QueryString["param1"];

            //process parameters received

            //send FILE in response
            Response.Clear();
            Response.WriteFile(@"C:\Users\Xyz\Desktop\xyz.xml");
        }
    }
}

The above code will send default response object with file, but I want to send only FILE without any default response.

Upvotes: 1

Views: 1530

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

You are better of writing a generic ASHX handler for this job. This is more lightweight than an entire WebForm (which in reality is a generic handler but with ton of additional crap that you don't need for this purpose)

public class DownloadFileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //get parameters
        string str = context.Request.QueryString["param1"];

        //process parameters received

        // set content type
        context.Response.ContentType = "text/xml";

        //send FILE in response
        context.Response.WriteFile(@"C:\Users\Xyz\Desktop\xyz.xml");
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

and then you could use http://example.com/downloadfile.ashx?param1=value1 from the client.

Upvotes: 3

Related Questions