将HTTP请求标头添加到WCF请求

Dor*_*hen 9 c# ajax http httprequest http-headers

我有一个由AJAX和C#应用程序使用的WCF服务,
我需要通过HTTP请求头发送一个参数.

在我的AJAX上,我添加了以下内容并且有效:

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

在WCF服务器端,我执行以下操作以获取标头:

string adminGUID = System.Web.HttpContext.Current.Request.Headers["AdminGUID"];
Run Code Online (Sandbox Code Playgroud)

什么是C#等价物?如何发送也将由我的WCF服务器使用的http请求标头?

我需要将参数添加到HTTP请求标头而不是消息标头,

谢谢!

Dor*_*hen 24

最简单的方法是使用WebOperationContext,方法如下:

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();
}
Run Code Online (Sandbox Code Playgroud)

摘自这篇文章