I can't get httpWorkerRequest.ReadEntityBody() to work !!!

G

Guest

I am trying to write a httpModule that will process file uploads but I can't
get
httpWorkerRequest.GetPreloadedEntityBody() or
httpWorkerRequest.ReadEntityBody()
to work at all!

Thanks

- Will


httpWorkerRequest.GetPreloadedEntityBody() (always returns 0 bytes)
httpWorkerRequest.ReadEntityBody() (always returns 0 bytes)

httpWorkerRequest.HasEntityBody() (looks good)
httpWorkerRequest.GetTotalEntityBodyLength() (looks good)
httpWorkerRequest.IsEntireEntityBodyIsPreloaded() (looks good)


In pseudo code:

1) My BeginRequest() is called (works).

2) I test to see if the page is an upload page (works).

3) httpWorkerRequest.GetPreloadedEntityBody() is called. (this always
returns 0 bytes).

4) httpWorkerRequest.IsEntireEntityBodyIsPreloaded() is called to make sure
there are bytes still
left to retrieve.

5) A read loop is started to retrieve the rest of the bytes

5a) httpWorkerRequest.ReadEntityBody() is called to get a chunck of data
(always returns 0 bytes)
5b) bytesReceived += bytesRead;
5c) next iteration of the loop is started


======================================================

using System;
using System.Collections;

using System.Configuration;

using System.Text;

using System.Threading;

using System.IO;

using System.Reflection;

using System.Web;

using System.Xml;

using System.Xml.XPath;



public sealed class UploadModule : IHttpModule

{

private const Int32 uploadBufferSize = 16530137;

private ReaderWriterLock rwl;

public void Dispose()

{

}

#region Properties

public static object GetTotalSize(string guid)

{

ReaderWriterLock srwl = new ReaderWriterLock();

try

{

srwl.AcquireReaderLock(1000);

return HttpContext.Current.Application["contentLength_" + guid];

}

finally

{

srwl.ReleaseReaderLock();

}

}

public static object GetCurrentSize(string guid)

{

ReaderWriterLock srwl = new ReaderWriterLock();

try

{

srwl.AcquireReaderLock(1000);

return HttpContext.Current.Application["uploadProgress_" + guid];

}

finally

{

srwl.ReleaseReaderLock();

}

}

private object TotalSize

{

set

{

if (rwl == null)

rwl = new ReaderWriterLock();

rwl.AcquireWriterLock(1000);

try

{

if (value == null)

HttpContext.Current.Application.Remove(contentLengthKey);

HttpContext.Current.Application[contentLengthKey] = value;

}

finally

{

rwl.ReleaseWriterLock();

}

}

}

private object CurrentSize

{

set

{

rwl.AcquireWriterLock(1000);

try

{

if (value == null)

HttpContext.Current.Application.Remove(uploadProgressKey);

HttpContext.Current.Application[uploadProgressKey] = value;

}

finally

{

rwl.ReleaseWriterLock();

}

}

}

#endregion Properties

/// <summary>

/// Contains the unique variable name used to track the upload progress for
this current upload.

/// The contects must be in the format of "uploadProgress_" + GUID

/// </summary>

private string uploadProgressKey;

/// <summary>

/// Contains the unique variable name used to track the upload total size
for this current upload.

/// The contects must be in the format of "contentLength_" + GUID

/// </summary>

private string contentLengthKey;

public void Init(HttpApplication httpApplication)

{

WriteLine2Log("Init()");

//Call this event to notify a module that new request is beginning.

httpApplication.BeginRequest += new EventHandler(context_BeginRequest);

//Call this event to notify the module of an error that occurs during
request processing.

httpApplication.Error += new EventHandler(context_Error);

//Call this event to notify the module that the request is ending.

httpApplication.EndRequest += new EventHandler(context_EndRequest);

}

private bool IsUploadPage(HttpApplication httpApplication)

{

HttpWorkerRequest httpWorkerRequest

= GetWorkerRequest(httpApplication.Context);

string uploadGuid

= httpApplication.Context.Request.Params["UploadGuid"];

string contentType

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

bool HasEntityBody = httpWorkerRequest.HasEntityBody();

//bool HasUploadGuid = (httpApplication.Context.Request.Params["UploadGuid"]
!= null);

bool IsMultipartFormData = (contentType != null &&
contentType.ToLower().StartsWith("multipart/form-data"));

if (HasEntityBody && /*HasUploadGuid &&*/ IsMultipartFormData)

{

//WriteLine2Log("IsUploadPage():true");

return true;

}

else

{

//WriteLine2Log("IsUploadPage():false");

//WriteLine2Log("IsUploadPage():HasEntityBody = " + HasEntityBody);

//WriteLine2Log("IsUploadPage():HasUploadGuid = " + HasUploadGuid);

//WriteLine2Log("IsUploadPage():IsMultipartFormData = " +
IsMultipartFormData);

return false;

}

}

private void context_BeginRequest(object sender, EventArgs e)

{

WriteLine2Log("context_BeginRequest()");

HttpApplication httpApplication

= sender as HttpApplication;

HttpWorkerRequest httpWorkerRequest

= GetWorkerRequest(httpApplication.Context);

StreamWriter tempStreamWriter

= GetTempFileStream();

httpApplication.Context.Response.Write("<h1><font
color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");

WriteLine2Log("context_BeginRequest(): contentType: " +
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType));

WriteLine2Log("context_BeginRequest(): contentLengthHeader: " +
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));

WriteLine2Log("context_BeginRequest(): rawUrl: " +
httpWorkerRequest.GetRawUrl());

rwl = new ReaderWriterLock();

//Returns true if the request contains body data.

bool thisIsAnUploadPage

= IsUploadPage(httpApplication);

if (thisIsAnUploadPage)

{

WriteLine2Log("context_BeginRequest(): thisIsAnUploadPage = true");

Int64 bytesReceived = 0;

Int64 contentLength = 0;

string contentLengthHeader

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength);

if (contentLengthHeader != null)

{

try

{

contentLength = Int64.Parse(contentLengthHeader);

}

catch (Exception ex)

{

throw new HttpException(400, "Bad Request", ex);

}

}

Int64 bytesRemaining

= contentLength;

uploadProgressKey

= "uploadProgress_" + httpApplication.Context.Request.Params["UploadGuid"];

contentLengthKey

= "contentLength_" + httpApplication.Context.Request.Params["UploadGuid"];

Int32 bufferSize = uploadBufferSize;

string contentType

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

//Update the application variable tracking total bytes to upload.

WriteLine2Log("context_BeginRequest(): TotalSize = " + contentLength);

TotalSize = contentLength;

if (contentLength > 0)

{

//Returns the bytes of the HTTP request body that has currently been read.

byte[] incommingData

= httpWorkerRequest.GetPreloadedEntityBody();

if (incommingData != null)

{

bytesReceived = incommingData.Length;

WriteLine2Log("context_BeginRequest(): incommingData.Length = " +
incommingData.Length);

}

else

{

WriteLine2Log("context_BeginRequest(): incommingData.Length = " + null);

bytesReceived = 0;

}

//Determine if there are additional bytes to read.

if (httpWorkerRequest.IsEntireEntityBodyIsPreloaded() == false)

{

WriteLine2Log("context_BeginRequest(): IsEntireEntityBodyIsPreloaded =
false");

Int32 loopCounter = 0;

while (bytesReceived < contentLength)

{

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
");

//Last chunck may be partial.

if (bytesReceived + bufferSize >
httpApplication.Context.Request.ContentLength)

{

bufferSize = httpApplication.Context.Request.ContentLength -
(int)bytesReceived;

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
Last chunk detected bufferSize = " + bufferSize);

}

incommingData = new byte[bufferSize];

//Update the application variable tracking upload progress.

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
IsEntireEntityBodyIsPreloaded = " +
httpWorkerRequest.IsEntireEntityBodyIsPreloaded().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
HasEntityBody = " + httpWorkerRequest.HasEntityBody().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
GetTotalEntityBodyLength = " +
httpWorkerRequest.GetTotalEntityBodyLength().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
IsClientConnected = " + httpWorkerRequest.IsClientConnected().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
RequestTraceIdentifier = " +
httpWorkerRequest.RequestTraceIdentifier.ToString());

CurrentSize

= bytesReceived;

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() + "):
CurrentSize = " + bytesReceived);

Int32 bytesRead

= httpWorkerRequest.ReadEntityBody(incommingData, bufferSize);

bytesReceived += bytesRead;

loopCounter++;

if (loopCounter > 20)

{

httpApplication.CompleteRequest();

break;

}

}

}

else

{

WriteLine2Log("context_BeginRequest(): IsEntireEntityBodyIsPreloaded =
true");

}

httpApplication.CompleteRequest();

//PushRequestToIIS(httpWorkerRequest, uploadedData);

}

}

}

private void context_EndRequest(object sender, EventArgs e)

{

WriteLine2Log("context_EndRequest()");

HttpApplication httpApplication

= sender as HttpApplication;

httpApplication.Context.Response.Write("<hr><h1><font
color=red>HelloWorldModule: End of Request</font></h1>");

//check whether the page is an upload page

if (IsUploadPage(httpApplication))

{

TotalSize = null;

CurrentSize = null;

}

}

private void context_Error(object sender, EventArgs e)

{

WriteLine2Log("context_Error()");

HttpApplication httpApplication

= sender as HttpApplication;

//check whether the page is an upload page

if (IsUploadPage(httpApplication))

{

TotalSize = null;

CurrentSize = null;

}

}

HttpWorkerRequest GetWorkerRequest(HttpContext context)

{

IServiceProvider provider = (IServiceProvider)HttpContext.Current;

HttpWorkerRequest httpWorkerRequest

= (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

return httpWorkerRequest;

}

private void PushRequestToIIS(HttpWorkerRequest request, byte[] textParts)

{

WriteLine2Log("PushRequestToIIS()");

BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;

Type type = request.GetType();

while ((type != null) && (type.FullName !=
"System.Web.Hosting.ISAPIWorkerRequest"))

type = type.BaseType;

if (type != null)

{

type.GetField("_contentAvailLength", bindingFlags).SetValue(request,
textParts.Length);

type.GetField("_contentTotalLength", bindingFlags).SetValue(request,
textParts.Length);

type.GetField("_preloadedContent", bindingFlags).SetValue(request,
textParts);

type.GetField("_preloadedContentRead", bindingFlags).SetValue(request,
true);

}

}

StreamWriter GetTempFileStream()

{

string tempFilePath

= System.IO.Path.GetTempPath();

string tempFileName

= System.IO.Path.GetRandomFileName();

string tempFileExtension

= ".pdis";

tempFilePath += tempFileName + tempFileExtension;

FileInfo fileInfo

= new FileInfo(tempFilePath);

FileStream fileStream

= fileInfo_OpenWrite();

StreamWriter streamWriter

= new StreamWriter(fileStream);

return streamWriter;

}

StreamWriter GetLogFileStream()

{

string logFilePath

= @"c:\pdislog.txt";

FileInfo fileInfo

= new FileInfo(logFilePath);

StreamWriter streamWriter

= fileInfo.AppendText();

//FileStream fileStream

// = fileInfo_OpenWrite();

//StreamWriter streamWriter

// = new StreamWriter(fileStream);

return streamWriter;

}

private void WriteLine2Log(string line)

{

string logPath

= @"C:\Documents and Settings\wbaldwin\My Documents\Visual Studio
2005\WebSites\Upload\Uploads\log.txt";

FileInfo fileInfo

= new FileInfo(logPath);

StreamWriter streamWriter;

if (!fileInfo.Exists)

{

streamWriter

= fileInfo.CreateText();

}

else

{

streamWriter

= File.AppendText(logPath);

}

streamWriter.WriteLine(DateTime.Now.ToShortTimeString() + ": " + line);

streamWriter.Close();

}

}
 
G

Guest

Now when I call GetBytesRead() I am getting this exception.

- Will

[HttpException (0x80004005): The operation is not supported.]

System.Web.Hosting.ISAPIWorkerRequest.GetBytesRead() +54

UploadModule.context_BeginRequest(Object sender, EventArgs e) +1599

System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+92

System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&
completedSynchronously) +64

I am trying to write a httpModule that will process file uploads but I
can't get
httpWorkerRequest.GetPreloadedEntityBody() or
httpWorkerRequest.ReadEntityBody()
to work at all!

Thanks

- Will


httpWorkerRequest.GetPreloadedEntityBody() (always returns 0 bytes)
httpWorkerRequest.ReadEntityBody() (always returns 0 bytes)

httpWorkerRequest.HasEntityBody() (looks good)
httpWorkerRequest.GetTotalEntityBodyLength() (looks good)
httpWorkerRequest.IsEntireEntityBodyIsPreloaded() (looks good)


In pseudo code:

1) My BeginRequest() is called (works).

2) I test to see if the page is an upload page (works).

3) httpWorkerRequest.GetPreloadedEntityBody() is called. (this always
returns 0 bytes).

4) httpWorkerRequest.IsEntireEntityBodyIsPreloaded() is called to make
sure there are bytes still
left to retrieve.

5) A read loop is started to retrieve the rest of the bytes

5a) httpWorkerRequest.ReadEntityBody() is called to get a chunck of
data (always returns 0 bytes)
5b) bytesReceived += bytesRead;
5c) next iteration of the loop is started


======================================================

using System;
using System.Collections;

using System.Configuration;

using System.Text;

using System.Threading;

using System.IO;

using System.Reflection;

using System.Web;

using System.Xml;

using System.Xml.XPath;



public sealed class UploadModule : IHttpModule

{

private const Int32 uploadBufferSize = 16530137;

private ReaderWriterLock rwl;

public void Dispose()

{

}

#region Properties

public static object GetTotalSize(string guid)

{

ReaderWriterLock srwl = new ReaderWriterLock();

try

{

srwl.AcquireReaderLock(1000);

return HttpContext.Current.Application["contentLength_" + guid];

}

finally

{

srwl.ReleaseReaderLock();

}

}

public static object GetCurrentSize(string guid)

{

ReaderWriterLock srwl = new ReaderWriterLock();

try

{

srwl.AcquireReaderLock(1000);

return HttpContext.Current.Application["uploadProgress_" + guid];

}

finally

{

srwl.ReleaseReaderLock();

}

}

private object TotalSize

{

set

{

if (rwl == null)

rwl = new ReaderWriterLock();

rwl.AcquireWriterLock(1000);

try

{

if (value == null)

HttpContext.Current.Application.Remove(contentLengthKey);

HttpContext.Current.Application[contentLengthKey] = value;

}

finally

{

rwl.ReleaseWriterLock();

}

}

}

private object CurrentSize

{

set

{

rwl.AcquireWriterLock(1000);

try

{

if (value == null)

HttpContext.Current.Application.Remove(uploadProgressKey);

HttpContext.Current.Application[uploadProgressKey] = value;

}

finally

{

rwl.ReleaseWriterLock();

}

}

}

#endregion Properties

/// <summary>

/// Contains the unique variable name used to track the upload progress
for this current upload.

/// The contects must be in the format of "uploadProgress_" + GUID

/// </summary>

private string uploadProgressKey;

/// <summary>

/// Contains the unique variable name used to track the upload total size
for this current upload.

/// The contects must be in the format of "contentLength_" + GUID

/// </summary>

private string contentLengthKey;

public void Init(HttpApplication httpApplication)

{

WriteLine2Log("Init()");

//Call this event to notify a module that new request is beginning.

httpApplication.BeginRequest += new EventHandler(context_BeginRequest);

//Call this event to notify the module of an error that occurs during
request processing.

httpApplication.Error += new EventHandler(context_Error);

//Call this event to notify the module that the request is ending.

httpApplication.EndRequest += new EventHandler(context_EndRequest);

}

private bool IsUploadPage(HttpApplication httpApplication)

{

HttpWorkerRequest httpWorkerRequest

= GetWorkerRequest(httpApplication.Context);

string uploadGuid

= httpApplication.Context.Request.Params["UploadGuid"];

string contentType

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

bool HasEntityBody = httpWorkerRequest.HasEntityBody();

//bool HasUploadGuid =
(httpApplication.Context.Request.Params["UploadGuid"] != null);

bool IsMultipartFormData = (contentType != null &&
contentType.ToLower().StartsWith("multipart/form-data"));

if (HasEntityBody && /*HasUploadGuid &&*/ IsMultipartFormData)

{

//WriteLine2Log("IsUploadPage():true");

return true;

}

else

{

//WriteLine2Log("IsUploadPage():false");

//WriteLine2Log("IsUploadPage():HasEntityBody = " + HasEntityBody);

//WriteLine2Log("IsUploadPage():HasUploadGuid = " + HasUploadGuid);

//WriteLine2Log("IsUploadPage():IsMultipartFormData = " +
IsMultipartFormData);

return false;

}

}

private void context_BeginRequest(object sender, EventArgs e)

{

WriteLine2Log("context_BeginRequest()");

HttpApplication httpApplication

= sender as HttpApplication;

HttpWorkerRequest httpWorkerRequest

= GetWorkerRequest(httpApplication.Context);

StreamWriter tempStreamWriter

= GetTempFileStream();

httpApplication.Context.Response.Write("<h1><font
color=red>HelloWorldModule: Beginning of Request</font></h1><hr>");

WriteLine2Log("context_BeginRequest(): contentType: " +
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType));

WriteLine2Log("context_BeginRequest(): contentLengthHeader: " +
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength));

WriteLine2Log("context_BeginRequest(): rawUrl: " +
httpWorkerRequest.GetRawUrl());

rwl = new ReaderWriterLock();

//Returns true if the request contains body data.

bool thisIsAnUploadPage

= IsUploadPage(httpApplication);

if (thisIsAnUploadPage)

{

WriteLine2Log("context_BeginRequest(): thisIsAnUploadPage = true");

Int64 bytesReceived = 0;

Int64 contentLength = 0;

string contentLengthHeader

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength);

if (contentLengthHeader != null)

{

try

{

contentLength = Int64.Parse(contentLengthHeader);

}

catch (Exception ex)

{

throw new HttpException(400, "Bad Request", ex);

}

}

Int64 bytesRemaining

= contentLength;

uploadProgressKey

= "uploadProgress_" +
httpApplication.Context.Request.Params["UploadGuid"];

contentLengthKey

= "contentLength_" + httpApplication.Context.Request.Params["UploadGuid"];

Int32 bufferSize = uploadBufferSize;

string contentType

=
httpWorkerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentType);

//Update the application variable tracking total bytes to upload.

WriteLine2Log("context_BeginRequest(): TotalSize = " + contentLength);

TotalSize = contentLength;

if (contentLength > 0)

{

//Returns the bytes of the HTTP request body that has currently been read.

byte[] incommingData

= httpWorkerRequest.GetPreloadedEntityBody();

if (incommingData != null)

{

bytesReceived = incommingData.Length;

WriteLine2Log("context_BeginRequest(): incommingData.Length = " +
incommingData.Length);

}

else

{

WriteLine2Log("context_BeginRequest(): incommingData.Length = " + null);

bytesReceived = 0;

}

//Determine if there are additional bytes to read.

if (httpWorkerRequest.IsEntireEntityBodyIsPreloaded() == false)

{

WriteLine2Log("context_BeginRequest(): IsEntireEntityBodyIsPreloaded =
false");

Int32 loopCounter = 0;

while (bytesReceived < contentLength)

{

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): ");

//Last chunck may be partial.

if (bytesReceived + bufferSize >
httpApplication.Context.Request.ContentLength)

{

bufferSize = httpApplication.Context.Request.ContentLength -
(int)bytesReceived;

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): Last chunk detected bufferSize = " + bufferSize);

}

incommingData = new byte[bufferSize];

//Update the application variable tracking upload progress.

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): IsEntireEntityBodyIsPreloaded = " +
httpWorkerRequest.IsEntireEntityBodyIsPreloaded().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): HasEntityBody = " + httpWorkerRequest.HasEntityBody().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): GetTotalEntityBodyLength = " +
httpWorkerRequest.GetTotalEntityBodyLength().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): IsClientConnected = " +
httpWorkerRequest.IsClientConnected().ToString());

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): RequestTraceIdentifier = " +
httpWorkerRequest.RequestTraceIdentifier.ToString());

CurrentSize

= bytesReceived;

WriteLine2Log("context_BeginRequest(): loop(" + loopCounter.ToString() +
"): CurrentSize = " + bytesReceived);

Int32 bytesRead

= httpWorkerRequest.ReadEntityBody(incommingData, bufferSize);

bytesReceived += bytesRead;

loopCounter++;

if (loopCounter > 20)

{

httpApplication.CompleteRequest();

break;

}

}

}

else

{

WriteLine2Log("context_BeginRequest(): IsEntireEntityBodyIsPreloaded =
true");

}

httpApplication.CompleteRequest();

//PushRequestToIIS(httpWorkerRequest, uploadedData);

}

}

}

private void context_EndRequest(object sender, EventArgs e)

{

WriteLine2Log("context_EndRequest()");

HttpApplication httpApplication

= sender as HttpApplication;

httpApplication.Context.Response.Write("<hr><h1><font
color=red>HelloWorldModule: End of Request</font></h1>");

//check whether the page is an upload page

if (IsUploadPage(httpApplication))

{

TotalSize = null;

CurrentSize = null;

}

}

private void context_Error(object sender, EventArgs e)

{

WriteLine2Log("context_Error()");

HttpApplication httpApplication

= sender as HttpApplication;

//check whether the page is an upload page

if (IsUploadPage(httpApplication))

{

TotalSize = null;

CurrentSize = null;

}

}

HttpWorkerRequest GetWorkerRequest(HttpContext context)

{

IServiceProvider provider = (IServiceProvider)HttpContext.Current;

HttpWorkerRequest httpWorkerRequest

= (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

return httpWorkerRequest;

}

private void PushRequestToIIS(HttpWorkerRequest request, byte[] textParts)

{

WriteLine2Log("PushRequestToIIS()");

BindingFlags bindingFlags = BindingFlags.Instance |
BindingFlags.NonPublic;

Type type = request.GetType();

while ((type != null) && (type.FullName !=
"System.Web.Hosting.ISAPIWorkerRequest"))

type = type.BaseType;

if (type != null)

{

type.GetField("_contentAvailLength", bindingFlags).SetValue(request,
textParts.Length);

type.GetField("_contentTotalLength", bindingFlags).SetValue(request,
textParts.Length);

type.GetField("_preloadedContent", bindingFlags).SetValue(request,
textParts);

type.GetField("_preloadedContentRead", bindingFlags).SetValue(request,
true);

}

}

StreamWriter GetTempFileStream()

{

string tempFilePath

= System.IO.Path.GetTempPath();

string tempFileName

= System.IO.Path.GetRandomFileName();

string tempFileExtension

= ".pdis";

tempFilePath += tempFileName + tempFileExtension;

FileInfo fileInfo

= new FileInfo(tempFilePath);

FileStream fileStream

= fileInfo_OpenWrite();

StreamWriter streamWriter

= new StreamWriter(fileStream);

return streamWriter;

}

StreamWriter GetLogFileStream()

{

string logFilePath

= @"c:\pdislog.txt";

FileInfo fileInfo

= new FileInfo(logFilePath);

StreamWriter streamWriter

= fileInfo.AppendText();

//FileStream fileStream

// = fileInfo_OpenWrite();

//StreamWriter streamWriter

// = new StreamWriter(fileStream);

return streamWriter;

}

private void WriteLine2Log(string line)

{

string logPath

= @"C:\Documents and Settings\wbaldwin\My Documents\Visual Studio
2005\WebSites\Upload\Uploads\log.txt";

FileInfo fileInfo

= new FileInfo(logPath);

StreamWriter streamWriter;

if (!fileInfo.Exists)

{

streamWriter

= fileInfo.CreateText();

}

else

{

streamWriter

= File.AppendText(logPath);

}

streamWriter.WriteLine(DateTime.Now.ToShortTimeString() + ": " + line);

streamWriter.Close();

}

}
 
S

Steven Cheng[MSFT]

Hi Will,

Welcome to the ASP.NET newsgroup.

From your description and the code snippet you provided, you're buiding an
ASP.NET Httpmodule to intercept file upload requests. And you use the
HttpWorkerRequest class to manipulate the http request message in
httpmodule. However , you find that some of the HttpWorkerRequest
properties and method dosn't return the expecte value and you also get some
other exceptions when try calling some certain method, correct?

Based on my experience, for ASP.NET httpmodule or handler, they're high
level components which should access the well encapsulated and implemented
class and interfaces. The HttpWorkerRequest class is a raw abstract class
which is not quite expected to directly used by our application code unless
we're developing a custom asp.net hosting application. Instead, the
HttpRequest/HttpResponse class are the concrete implemented component
classes we should use in our page or module/handler components. For file
uploading, the HttpRequest class contains the "Files" property which can
help us access the uploaded file streams in the Multi-Part form request.
e.g:

========================
public class FUloadHttpModule : IHttpModule
{
public FUloadHttpModule()
{

}

#region IHttpModule Members

public void Dispose()
{

}

public void Init(HttpApplication context)
{
context.BeginRequest +=new EventHandler(BeginRequest);


}

#endregion


protected void BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext ctx = app.Context;
HttpRequest request = ctx.Request;
HttpResponse response = ctx.Response;

if (request.RawUrl.EndsWith("upload.aspx") & request.Files.Count>0)
{
foreach (string key in request.Files.Keys)
{
response.Write("<br>" + key + ", " +
request.Files[key].ContentType);

}

response.End();

}


}
}
=====================

Hope this helps.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top