WebServices应用(二)

[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>

 

转载于:https://www.cnblogs.com/shoushangdeyu/p/4489002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值