[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); } }
一、上面的description必不可少,下面的scriptmethod 中应该指的是js之类脚本调用的时候容许httpget方法获取,而且显示为json格式;这里须要有一点注意的,前台调用的时候,咱们直接输出到页面就能够了,js能够获取的到,若是是后台程序获取的话,web
咱们在编写webservice的时候方法必定要是带返回值的,有利于其余程序进一步操做。上面的能够看作是写给js调用的webservice,下面看一个是写给后台程序调用的webservice,具体代码以下,eg:json
public class Caculate : WebService { [WebMethod(Description = "加法")] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public int Add(int i, int j) { return i + j; } }
而后咱们在后台调用便可,代码以下,eg:app
protected void Page_Load(object sender, EventArgs e) { CaculateSoap cs=new CaculateSoapClient(); Response.Write(cs.Add(1, 5)); }
咱们引用的webservice要是变更的话,记得右键更新服务引用,这个时候会在webconfig中或者app.config中生成几行没有用的代码,删掉便可。spa
有的时候须要在webservice的webconfig中添加以下代码,eg:code
<webServices> <protocols> <add name= "HttpPost"/> <add name= "HttpGet"/> </protocols> </webServices>