Add Header to WebRequest

Aug 30, 2011 at 4: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.


Aug 30, 2011 at 7: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;

Aug 31, 2011 at 1:54 AM

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