C# – Need Help With HttpWebRequest object


I'm trying to build a proxy module for .NET, but I'm having trouble copying the Headers from the current request to the new request. I am setting the headers of the new request, because I want the proxy to support SOAP requests. Here is a portion of my code. I can post everything if need, but this is the only part that seems related to the issue I am having:

HttpApplication app = (HttpApplication)sender;   // sender from context.BeginRequest event
HttpRequest crntReq = app.Request;  // set a reference to request object for easier access

HttpWebRequest proxyReq = (HttpWebRequest)HttpWebRequest.Create(crntReq.Url.AbsoluteUri);

// parse headers from current httpcontext.request.headers and add each name->value to the 
// new request object
foreach (string header in crntReq.Headers)
    proxyReq.Headers.Add(header, crntReq.Headers[header]);      // throws exception :(                  

When my code hits the foreach loop, it throws an exception for the Headers.Add function. I'm assuming the collection has access restrictions, for security purposes. It appears that some of the header values are accessible with properties for the HttpWebRequest object itself. However in this case I'd rather get rid of the abstraction and set the properties manually. The exception that I'm receiving is:
{"This header must be modified using the appropriate property.\r\nParameter name: name"}

Thanks in advance for your help,


Best Solution

Some of the headers are actually exposed as properties directly on the HttpWebRequest object. These headers you are not allowed to set directly. e.g HttpWebRequest,ContentType and HttpWebRequest.UserAgent

You will need to update these properties directly and avoid setting them via the Headers property.