C#调用WebService服务(动态调用)

本文介绍了如何在C#中动态调用WebService服务。首先,详细讲解了创建WebService服务的过程,接着阐述了使用Visual Studio添加服务引用并生成代理类的方法。最后,文章重点讨论了动态调用服务的步骤,提供了详细的参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 创建WebService

using System;
using System.Web.Services;

namespace WebService1
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Description="测试服务")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod(Description="Hello World")]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod(Description="A加B")]
        public int Add(int a, int b)
        {
            return a + b;
        }

        [WebMethod(Description="获取时间")]
        public string GetDate()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}

服务创建后,在浏览器中输入服务地址,可以看到如下图所示。



2 通过Visual Studio添加服务引用

通过Visual Studio添加服务引用相当方便,只需要在Visual Studio中选择添加服务引用,便可以生成代理类,在项目中通过代理调用服务,如下图所示。




添加服务引用以后,在项目解决方案中多了Service References和app.config,如下图所示。



ServiceReference1就是上面添加的服务,app.config是服务的配置文件,app.config里面的配置大致如下,当服务地址改变时,修改endpoint里的address即可。

<!--app.config文件配置-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值