11

I have a WCF service consume by both AJAX and C# application,
I need to send a parameter through the HTTP request header.

On my AJAX I have added the following and it works:

$.ajax({
    type: "POST",
    url: this.tenantAdminService,
    beforeSend: function (req, methodName)
    {
        req.setRequestHeader("AdminGUID", adminGuid);
    }

and on the WCF server side I do the following to Get the header:

string adminGUID = System.Web.HttpContext.Current.Request.Headers["AdminGUID"];

What is the C# equivalent? How can I send the http request header that will also be consume by my WCF server?

I need to add the parameter to HTTP request header and not to the message header,

Thanks!

Marvin Dickhaus
  • 785
  • 12
  • 27
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161

2 Answers2

27

The simplest way to this is using WebOperationContext at the following way:

Service1Client serviceClient = new Service1Client();
using (new System.ServiceModel.OperationContextScope((System.ServiceModel.IClientChannel)serviceClient.InnerChannel))
{
    System.ServiceModel.Web.WebOperationContext.Current.OutgoingRequest.Headers.Add("AdminGUID", "someGUID");
    serviceClient.GetData();
}

Taken from this post

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
-2

Make a new WebRequest object of type HttpWebRequest. Set the header and get the response.

WebRequest req = HttpWebRequest.Create("myURL") as HttpWebRequest;
req.Headers.Add("AdminGUID", "value");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

for a more in depth example of webrequest, see this page

Ali Khalid
  • 1,345
  • 8
  • 19
  • Can I do this in a neater way? so that I wont have to put URL? since I already have service reference that contains all methods – Dor Cohen Dec 13 '12 at 09:20
  • You add the web service directly to your project c#. VS will automatically generate classes for you to call your web service directly but it might not give the option to add a request header, when calling the web service. – Ali Khalid Dec 13 '12 at 09:22