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即可。
<
本文介绍了如何在C#中动态调用WebService服务。首先,详细讲解了创建WebService服务的过程,接着阐述了使用Visual Studio添加服务引用并生成代理类的方法。最后,文章重点讨论了动态调用服务的步骤,提供了详细的参考资料。
最低0.47元/天 解锁文章
1018

被折叠的 条评论
为什么被折叠?



