如何从外部服务器调用C#WebService中的JSON方法

How to call JSON methods from C# WebService from external server

本文关键字:中的 JSON 方法 C#WebService 调用 从外部 服务器      更新时间:2023-09-26

如何在HTML5/JavaScript网站中使用asp.net web服务(c#)?并且web服务与客户端不在同一个站点中,因此这将是一个跨域请求。

我在web编程方面有一点经验,在将我的所有asp.net页面移动到HTML5和JS以获得更快的界面时,我很难将我的web服务连接到JS,JSON就是答案,收到的信息从2Kb下降到128字节,所以在移动设备上,它在某种程度上是有用的

第一/服务器端

mywebservice.asmx

下一个web服务将托管在site.com 网站上

那么地址将是"Site.com/MYWS.asmx/JSONMethod"

[WebService(Namespace = "http://...")]
[System.Web.Script.Services.ScriptService]
public class MYWS
{
    [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string JSONMethod(/*ParType ParName, ParType ParName2,.. etc*/)
        {
                List<object> tempobjects = new List<object>();
                tempobjects.Add(new { ID = id, Val = val /*more params=> ParName= "ParValue", etc..*/ });
                var retVal = new JavaScriptSerializer().Serialize(tempobjects.ToArray());
                Context.Response.ContentType = "application/json";
                var p = "";
                if (Context.Request.Params.AllKeys.Contains("callback") == true)
                    p = Context.Request.Params["callback"].ToString();
        Context.Response.Write(string.Format(CultureInfo.InvariantCulture, "{0}({1})", p, retVal));
        }
}

第二方/客户端

myJS.js

function MyJSMethod(){
$.ajax({
    url: "Site.com/MYWS.asmx/JSONMethod",
    data:{ParName: "parValue"/*, ParName2... etc*/},
    type:"GET",
    dataType:"jsonp" //if the method
    })
    .done(
        function(data){
            //Do what you need with the json data retrieved
            //... CODE HERE ...
            //In case you need to call a method from another js being used
            //window["JSmethod"](data)//if the json received is needed
        }
    ).fail(function(jqXHR, textStatus, errorThrown ){
    alert(jqXHR);
    alert(textStatus);
    alert(errorThrown);
    });
}

希望这对你和我一样有效。祝你好运,编码快乐。

-Poncho