1

我正在尝试从基于 ASP.NET 的 jQuery 移动网站进行 Web 服务调用。Web 服务采用 post 参数并返回 XML。我无法更改网络服务端。

我面临跨域问题,据我了解,我需要使用代理。

我正在考虑使用通用处理程序,但我不知道该怎么做。

我的服务方法如下所示:

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

并取 Post 参数

在 c# 中这样做的好方法是什么?

谢谢

4

2 回答 2

2

看看这个问题:Accessing web Service from jQuery - cross domain

作为替代方案,您还可以创建一个使用 jQuery Ajax 调用的 HttpHandler。然后,处理程序可以调用 Web 服务并将输出写入 Http 响应。

于 2012-10-09T20:17:24.023 回答
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>");
                }
            });
        });
    });

现在它正在工作:)

于 2012-10-10T15:54:55.920 回答