2012-07-29 60 views
1

从主叫方网站,我将有此代码:如何将请求标头传递给跨域的WCF服务?

$.ajax({ 
    type: "GET", 
    contentType: "application/json; charset=utf-8", 
    beforeSend: function (xhr) { 
     xhr.setRequestHeader("My-Key", '12345'); 
    }, 
    crossDomain: true, 
    xhrFields: { 
     withCredentials: true 
    }, 
    url: "http://targetsite.com/services/myservice/mymethod", 
    dataType: "json", 
    success: function (response) { 
    }, 
    error: function (message) { 
    } 
}); 

在目标网站服务我有以下代码:

public override void ProcessRequest(ref RequestContext requestContext) 
{ 
    var keys = (HttpRequestMessageProperty) 
        requestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name]; 
    string apiKey = prop.Headers["My-Key"];// this is coming null always 
} 

我得到apiKey空。你能让我知道我在这里做错了吗?

编辑:我这个尝试过在我的目标网站的Global.asax.cs开始请求事件,但没有运气:

//Enable Cross Domain WCF Configuration 
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    HttpContext.Current.Response.Cache.SetNoStore(); 
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
    string rqstMethod = HttpContext.Current.Request.Headers["Access-Control-Request-Method"]; 
    if (rqstMethod == "GET" || rqstMethod == "POST" || rqstMethod == "OPTIONS") 
    { 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); 
     HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "My-Key,X-Requested-With, Accept"); 
     HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "3628800"); 
     HttpContext.Current.Response.AddHeader("type", "application/json; charset=utf-8"); 
     HttpContext.Current.Response.End(); 
    } 
+1

您是在重述您先前的问题还是您只是不耐烦? – rene 2012-07-29 20:53:56

+0

jsonp不允许添加自定义请求标头:http://stackoverflow.com/questions/10546822/setrequestheader-does-not-work-in-jsonp-using-jquery – premsh 2013-06-21 23:27:03

回答

0

样JQuery的$就呼吁跨域与添加requestHeader

function TestingWCFRestWithJsonp() { 
        $.ajax({ 
         url: "http://targetsite.com/services/myservice/mymethod", 
         dataType: "jsonp", 
         type: "GET", 
         beforeSend: function(xhr) { 
             xhr.setRequestHeader("My-Key", '12345'); 
            }, 
         timeout: 10000, 
         jsonpCallback: "MyCallback", 
         success: function (data, textStatus, jqXHR) { 
          alert(data); 
         }, 
         error: function (jqXHR, textStatus, errorThrown) {alert('error'); 

         }, 
         complete: function (jqXHR, textStatus) {alert('complete'); 
         } 
        }); 
       } 
       function MyCallback(data) { 
        alert(data); 
       } 
+0

它仍然是空的。你有任何样品吗? – 2012-07-30 12:43:34

0

在您的服务上,尝试在响应中添加Access-Control-Allow-Origin标头。它指定允许哪些站点跨域调用您的服务。

访问控制允许来源:http://foo.example

哪里http://foo.example是发出请求的网站。你也可以为此使用通配符。 (请注意“访问控制 - 允许来源:*”!)