Adding HTTP request header to WCF request

23,126

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

Share:
23,126
Dor Cohen
Author by

Dor Cohen

C# and web developer

Updated on July 12, 2020

Comments

  • Dor Cohen
    Dor Cohen almost 4 years

    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!

  • Dor Cohen
    Dor Cohen over 11 years
    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
  • Ali Khalid
    Ali Khalid over 11 years
    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.
  • Shane van Wyk
    Shane van Wyk almost 11 years
    Thanks this helps a lot. Looks promising.