title: How to post data from a webform page to an HTTPHandler.ashx file?
body: <p>I have a web application project to support file transfer operations to vendor product backend. It's composed of 2 HTTPHandler files compiled into a website on a Win2003 server with IIS 6.0:</p>
  
  <ul>
  <li>UploadHandler.ashx</li>
  <li>DownloadHandler.ashx</li>
  </ul>
  
  <p>These files get "POSTed to" from a ColdFusion website that exposes the user interface. In a way, my job is done because these handlers work and have to be called from ColdFusion. </p>
  
  <p>Yet, I am very frustrated with my inability to get my own "test UI" (default.aspx) to use in my testing/refinement independent of ColdFusion. </p>
  
  <pre><code>&lt;asp:Button ID="DownloadButton" PostBackUrl="~/DownloadHandler.ashx"  runat="server" Text="Download"/&gt;
  </code></pre>
  
  <p>Using a PostBackUrl for Download works nicely - when the DownloadHandler.ashx is entered, it finds its key input value in <strong>context.Request.Form["txtRecordNumber"];</strong></p>
  
  <p>But I cannot use this technique for Upload because I have to do some processing <strong><em>(somehow read the bytes from the chosen fileupload1.postedfile into a FORM variable so my UploadHandler.ashx file can obtain its input from Request.Form as with Download)</em></strong>. </p>
  
  <p><a href="https://stackoverflow.com/questions/1279416" title="My first approach">My first approach tried using HTTPWebRequest</a> which seemed overly complex and I could never get to work. Symptoms began with a HTTP 401 status code and then morphed into a 302 status code so I researched other ideas.</p>
  
  <p>Here is my latest code snippet from my default.aspx:</p>
  
  <pre><code>protected void UploadHandlerButton_Click(object sender, EventArgs e)
  {
      if (FileUpload1.HasFile)
      {
          try
          {
              BuildFormData();
              //Server.Transfer("UploadHandler.ashx", true);
              Response.Redirect("~/UploadHandler.ashx");
          }
          catch (Exception someError)
          {
              LogText("FAILURE: " + someError.Message);
          }
      }
  }
  protected void BuildFormData()
  {
      BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
      int numBytes = FileUpload1.PostedFile.ContentLength;
      byte[] fileContent = b.ReadBytes(numBytes);
      objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
      b64fileName.Text = FileUpload1.PostedFile.FileName;
      // create arbitrary MetaData in a string
      strMetaData.Text = "recAuthorLoc=anyname1~udf:OPEAnalyst=anyname2~udf:Grant Number=0102030405";
  }
  </code></pre>
  
  <p>Attempts to use Server.Transfer (above) to my .ashx file result in an error: 
      <strong>error executing child request for UploadHandler.ashx</strong></p>
  
  <p>Attempts to use Response.Redirect (above) to my .ashx file result in GET (not POST) and Trace.axd of course shows nothing in the Form collection so that seems wrong too. </p>
  
  <p>I even tried clone-ing my .ashx file and created UploadPage.aspx (a webform with no HTML elements) and then tried:</p>
  
  <pre><code>Server.Transfer("UploadPage.aspx", true);
  //Response.Redirect("~/UploadPage.aspx");
  </code></pre>
  
  <p>Neither of those allow me to see the form data I need to see in Request.Form within my code that processes the Upload request. I am clearly missing something here...thanks in advance for helping. </p>
  
  <p><strong>EDIT-UPDATE:</strong>
  I think I can clarify my problem. When the UploadHandler.ashx is posted from ColdFusion, all of the input it needs is available in the FORM collection (e.g. Request.Form["fileData"] etc.)</p>
  
  <p>But when I use this <strong></strong> control it generates a postback to my launching web page (i.e. default.aspx). This enables me to refer to the content by means of <strong>FileUpload1.PostedFile</strong> as in: </p>
  
  <pre><code>protected void BuildFormData()
  {
      BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
      int numBytes = FileUpload1.PostedFile.ContentLength;
      byte[] fileContent = b.ReadBytes(numBytes);
      objBinaryData.Text = System.Text.Encoding.UTF8.GetString(fileContent);
      b64fileName.Text = FileUpload1.PostedFile.FileName;
  }
  </code></pre>
  
  <p>Yet I am <strong>not using</strong> the FileUpload1.PostedFile.SaveAs method to save the file somewhere on my web server. I need to somehow - forgive the language here - <strong><em>"re-post"</em></strong> this data to an entirely different file - namely, my UploadHandler.ashx handler. All the goofy techniques I've tried above fail to accomplish what I need. </p>
  
  <p><strong>EDIT-UPDATE (20 Aug 2009) - my final SOLUTION using Javascript:</strong></p>
  
  <pre><code>protected void UploadHandlerButton_Click(object sender, EventArgs e)
  {
      if (FileUpload1.HasFile)
      {
          try
          {
              ctlForm.Text = BuildFormData();
              String strJS = InjectJS("_xclick");
              ctlPostScript.Text = strJS;
          }
          catch (Exception someError)
          {
              LogText("FAILURE: " + someError.Message);
          }
      }
  }
  private String InjectJS(String strFormId)
  {
      StringBuilder strScript = new StringBuilder();
      strScript.Append("&lt;script language='javascript'&gt;");
      strScript.Append("var ctlForm1 = document.forms.namedItem('{0}');");
      strScript.Append("ctlForm1.submit();");
      strScript.Append("&lt;/script&gt;");
      return String.Format(strScript.ToString(), strFormId);
  }
  protected string BuildFormData()
  {
      BinaryReader b = new BinaryReader(FileUpload1.PostedFile.InputStream);
      int numBytes = FileUpload1.PostedFile.ContentLength;
      byte[] fileContent = b.ReadBytes(numBytes);
      // Convert the binary input into Base64 UUEncoded output.
      string base64String;
      base64String =
             System.Convert.ToBase64String(fileContent,
                                           0,
                                           fileContent.Length);
      objBinaryData.Text = base64String;
      b64fileName.Text = FileUpload1.PostedFile.FileName;
      // create arbitrary MetaData in a string
      strMetaData.Text = "recAuthorLoc=Patterson, Fred~udf:OPEAnalyst=Tiger Woods~udf:Grant Number=0102030405";
  
      StringBuilder strForm = new StringBuilder();
      strForm.Append("&lt;form id=\"_xclick\" name=\"_xclick\" target=\"_self\" action=\"http://localhost/HTTPHandleTRIM/UploadHandler.ashx\" method=\"post\"&gt;");
      strForm.Append("&lt;input type=\"hidden\" name=\"strTrimURL\"    value=\"{0}\" /&gt;");
      strForm.Append("&lt;input type=\"hidden\" name=\"objBinaryData\" value=\"{1}\" /&gt;");
      strForm.Append("&lt;input type=\"hidden\" name=\"b64fileName\"   value=\"{2}\" /&gt;");
      strForm.Append("&lt;input type=\"hidden\" name=\"strDocument\"   value=\"{3}\" /&gt;");
      strForm.Append("&lt;input type=\"hidden\" name=\"strMetaData\"   value=\"{4}\" /&gt;");
      strForm.Append("&lt;/form&gt;");
      return String.Format(strForm.ToString()
          , txtTrimURL.Text
          , objBinaryData.Text
          , b64fileName.Text
          , txtTrimRecordType.Text
          , strMetaData.Text);
  }
  </code></pre>