Adding HTTP request header to WCF request

可紊 提交于 2020-12-29 05:56:55

问题


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!


回答1:


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




回答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



来源:https://stackoverflow.com/questions/13856362/adding-http-request-header-to-wcf-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!