2012-10-09 44 views
1

我試圖從ASP.NET基礎上的jQuery移動網站進行web服務調用。 webservices採用post參數並返回一個XML。 我無法更改Web服務端。通過跨域XML使jquery發佈webservices調用

我正面臨跨域問題,從我的理解,我需要使用代理。

我想使用通用處理程序,但我不知道該怎麼做。

我的服務的方法看起來像這樣:

https://myserver.com/WCF/Info.svc/MyMehod1 
https://myserver.com/WCF/Info.svc/MyMehod2 

並採取POST參數

什麼會做,在C#中的好方法嗎?

感謝

回答

1

我終於得到它的工作。

對於那些誰有同樣的問題,

在客戶端上,我使用了一個通用的處理程序做Web服務調用和暴露的結果。

處理程序樣本:

public void ProcessRequest(HttpContext context) 
{ 
    string method = context.Request.QueryString["method"].ToString().ToLower(); 

    if (method == "MyMethod1") 
    { 
     context.Response.ContentType = "text/plain"; 
     context.Response.Write(CallWebService(method, param)); 
     context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    } 
    else if (method == "MyMethod2") 
    { 
     context.Response.ContentType = "text/plain"; 
     string param = "myparam"; 
     context.Response.Write(CallWebService(method, param)); 
     context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    } 
    else 
    { 
    //context.Response.ContentType = "text/plain"; 
    //context.Response.Write("Hello World"); 
    } 


} 

private string CallWebService(string method, string param) 
{ 
    string ServeurURL = "https://myserver.com"; 

    System.Net.WebRequest req = System.Net.WebRequest.Create(ServeurURL + method); 
    req.Method = "POST"; 

    byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(param); 
    req.ContentType = "text/xml"; 
    req.ContentLength = byteArray.Length; 
    System.IO.Stream reqstream = req.GetRequestStream(); 
    reqstream.Write(byteArray, 0, byteArray.Length); 
    reqstream.Close(); 

    System.Net.WebResponse wResponse = req.GetResponse(); 
    reqstream = wResponse.GetResponseStream(); 
    System.IO.StreamReader reader = new System.IO.StreamReader(reqstream); 
    string responseFromServer = reader.ReadToEnd(); 

    return responseFromServer; 
} 

的jQuery/Ajax調用:

jQuery(function() { 
     $('#btn1').click(function (e) { 
      e.preventDefault(); 
      jQuery.ajax({ 
       type: "GET", 
       url: "MyHandler.ashx", 
       data: "method=MyMethod1", 
       success: function (data) { 
        $('#display').html("<h1>" + data.toString() + "</h1>"); 
       } 
      }); 
     }); 
     $('#btn2').click(function (e) { 
      e.preventDefault(); 
      jQuery.ajax({ 
       type: "GET", 
       url: "MyHandler.ashx", 
       data: "method=MyMethod2", 
       success: function (data) { 
        $('#display').html("<h1>" + data.toString() + "</h1>"); 
       } 
      }); 
     }); 
    }); 

而現在它的工作:)

+1

嘿@Distwo,很高興爲你工作。只是一個提示:在這樣的情況下,用你選擇的答案來更新你的問題,而不是不接受答案,這可能是更好的禮儀。 –

+1

我以爲我可以標記爲接受答案,你是邏輯,我是相關的代碼,但它刪除了第一個...... :( – Distwo

+0

這是一個很好的解決方案,應該有更多的票。 – Tastybrownies

2

檢查這個問題了:Accessing web Service from jQuery - cross domain

作爲替代方案,你也可以創建您使用jQuery的Ajax調用一個HttpHandler。處理程序然後可以調用Web服務並將輸出寫入Http響應。

+0

我使用的HttpHandler的替代性和它的工作。 我會發布我的代碼,只要stackoverflow允許我,爲那些誰將面臨同樣的問題;) – Distwo