[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [ScriptService] public class Caculate : WebService { [WebMethod(Description = "加法")] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public void Add(int i, int j) { Context.Response.ContentType = "application/json"; var sum = new { Sum = i + j }; Context.Response.Write(sum); } }
1、上面的description必不可少,下面的scriptmethod 中应该指的是js之类脚本调用的时候允许httpget方法获取,并且显示为json格式;这里需要有一点注意的,前台调用的时候,我们直接输出到页面就可以了,js可以获取的到,如果是后台程序获取的话,
我们在编写webservice的时候方法一定要是带返回值的,有利于其他程序进一步操作。上面的可以看做是写给js调用的webservice,下面看一个是写给后台程序调用的webservice,具体代码如下,eg:
public class Caculate : WebService { [WebMethod(Description = "加法")] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public int Add(int i, int j) { return i + j; } }
然后我们在后台调用即可,代码如下,eg:
protected void Page_Load(object sender, EventArgs e) { CaculateSoap cs=new CaculateSoapClient(); Response.Write(cs.Add(1, 5)); }
我们引用的webservice要是变动的话,记得右键更新服务引用,这个时候会在webconfig中或者app.config中生成几行没有用的代码,删掉即可。
有的时候需要在webservice的webconfig中添加如下代码,eg:
<webServices> <protocols> <add name= "HttpPost"/> <add name= "HttpGet"/> </protocols> </webServices>