Wednesday, February 21, 2007

Servlets in .net?

Today I am writing a website using .net 2.0, and one of the pages needs to return a .pdf rather than HTML. So the return back needs to not output the normal html headers and content. But in ASPX, every webpage must contain at least this:
<html><body/></html>

But once that is emitted into the stream, I am not outputting a .pdf any more. So I needed to subvert the streaming of that content.

Here's what I did:
<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<% if (true)
{
Emit_Content();
}
else
{ %>
<html><body/></html>
<% } %>

Once the html tags were subverted, I was able to write the Emit_Content() function in Default2.aspx.cs. Note that byte array _buff and Int32 _got are member variables.

    /*
* Write out the contents of the
* pdf to the http response socket
*/
protected void Emit_Content()
{
try
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
"inline;filename=new.pdf");

Response.BinaryWrite(_buff, _got));
}
catch (Exception ex)
{
Response.Write("<html><body>" +
ex.Message + "</body></html>");
}
}

No comments: