This project has moved. For the latest updates, please go here.

Add Header to WebRequest

Aug 30, 2011 at 5:00 PM

Is it possible to add a custom header to an outgoing WebRequest - I have an ODATA feed that needs a shared secret to access and will need to add a special header to each request being made to the ODATA service.

thanks
Michael

Aug 30, 2011 at 8:47 PM

After looking at the latest AgFx source code for the WebLoadRequest - I created a custom LoadRequest (CustomLoadRequest) that includes a Dictionary<string,string> to hold any custom headers you want to include in the request. I override the CreateWebRequest method and iterate over the RequestCustomHeaders and add any headers that are in the Dictionary to the HttpWebRequest.  Then in the LoadRequest method of my ModelItem - instead of instanciating a standard WebLoadRequest, I create a CustomLoadRequest and add the custom header for the secret key that I need to be included.

Here is my source:

public LoadRequest GetLoadRequest(BrowseSessionsLoadContext browseLoadContext, Type objectType)
{
 var req = new CustomWebLoadRequest(browseLoadContext, new Uri(uri));
 req.RequestCustomHeaders["secretkey"] = "12345";
    
 return req;
}

public class CustomWebLoadRequest : WebLoadRequest
 {
  public Dictionary<string, string> RequestCustomHeaders = new Dictionary<string, string>();

  public CustomWebLoadRequest(LoadContext loadContext, Uri uri)
   : base(loadContext, uri) { }

  protected override HttpWebRequest CreateWebRequest()
  {
   Debug.Assert(Uri != null, "Null uri");
   HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(Uri);
   foreach (string headerName in RequestCustomHeaders.Keys)
   {
    hwr.Headers[headerName] = RequestCustomHeaders[headerName];
   }
   hwr.Method = Method;
   if (!String.IsNullOrEmpty(ContentType))
   {
    hwr.ContentType = ContentType;
   }

   return hwr;
  }
 }

Coordinator
Aug 31, 2011 at 2:54 AM

Looks good, nice work.  I'll think about adding similar functionality directly to WebLoadRequest in a future release.