2012-07-29 62 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是發出請求的網站。你也可以爲此使用通配符。 (請注意「訪問控制 - 允許來源:*」!)