Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding HTTP request header to WCF request

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!

like image 984
Dor Cohen Avatar asked Dec 13 '12 09:12

Dor Cohen


People also ask

How do I add a custom HTTP header to every WCF call?

A nice and easy way to pass that data is to use Message Headers. In WCF, to pass the custom header information along with method call, we need to implement custom inspector for client and service which will implement the BeforeSendRequest and AfterRecieveRequest methods to inject the custom header.

How do I add HTTP header to request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers. For example: oRequest = RequestBuilder:Build('GET', oURI) :AddHeader('MyCustomHeaderName','MyCustomHeaderValue') :AddHeader('MySecondHeader','MySecondHeaderValue') :Request.

What is HTTP request custom header?

Custom HTTP headers can be used to filter requests or specify a value for the Accept header. Some endpoints employ custom HTTP headers to filter data returned by a GET or POST request.


1 Answers

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

like image 101
Dor Cohen Avatar answered Oct 21 '22 17:10

Dor Cohen