在VS2010中不能直接创建ASP.NET Web 服务应用程序,
但是可以利用以下方法创建:
1.打开vs2010,文件--新建--项目---Visuio C#---web---ASP.NET 空Web应用程序,起名为TestWebService,确定
2.右击项目名称,---添加新项--Visual C#---web 服务--起名为MyService.asmx,点击确定
3.右击MyService.asmx---查看代码---添加两个方法,获取名字和年龄
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService {
public MyService () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]//必须要有的,为了说明,其下是一个方法,每一个方法前面都需要有。
public string getName()
{
return "Hope";
}
[WebMethod]
public string getAge()
{
return "25";
}
}
3.右击MyService.asmx,选择“在浏览器中查看”,即可检查本项目是否有语法错误.可以点击 getAge,getName获取值。
接下来写一下如何调用这个service.
在VS2010中,新建一个项目--web Form 应用程序。名字为:WindowsFormsApplication1
右击项目名称---添加服务引用。
添加引用之后,项目列表中会显示。
在窗口中拖入控件:
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
localhost.MyService obj = new localhost.MyService();
textBox1.Text = obj.getAge();
}
}
}
运行winform项目:执行结果如下:
本文介绍了在VS2010中如何创建C# Web Service的详细步骤,包括创建ASP.NET空Web应用程序,添加Web服务,编写服务方法,并展示了如何在另一个Web Form项目中调用该服务。
1630

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



