---
title: "在 Visual Studio 2012 中创建 ASP.Net Web Service （转）"
author: "sangei"
date: "2014-02-22T21:52:51Z"
tags: []
categories: ["编程语言"]
slug: "visual-studio-2012-asp-net-web-service"
draft: false
lastmod: "2014-02-22T21:52:51Z"
id: 2020576
url: "https://sangei.iteye.com/blog/2020576"
---

在 Visual Studio 2012 中创建 ASP.Net Web Service，步骤非常简单。如下：

**第一步：创建一个“ASP.Net Empty Web Application”项目**

![](http://img.my.csdn.net/uploads/201209/18/1347979771_8914.png)

创建一个“ASP.Net Empty Web Application”项目。你会看到一个进度条，显示 Visual Studio 2012 正在创建这个空的 ASP.Net Web Application。

![](http://img.my.csdn.net/uploads/201209/18/1347980026_7474.png)

经历短暂的等待之后，一个空的 ASP.Net Web Application 就建好了，它仅包含一个站点配制文件（Web.config），其余的什么也没有。

![](http://img.my.csdn.net/uploads/201209/18/1347980604_6247.png)

**第二步：在项目中添加“Web Service”新项目**

在 Visual Studio 2012 的 Solution Explorer 中，选中当前的这个 project，添加新项目（右键菜单：Add --&gt; New Item），选择“Web Service”这种类型：

![](http://img.my.csdn.net/uploads/201209/18/1347980751_7771.png)

![](http://img.my.csdn.net/uploads/201209/18/1347980849_5417.png)

**第三步：编码、运行**

添加完Web Service这种 new item 之后，Visual Studio 已经替我们写了个示范的Web方法了：

![](http://img.my.csdn.net/uploads/201209/18/1347980996_1506.png)

直接按快捷键 F5 就可以看到结果：

![](http://img.my.csdn.net/uploads/201209/18/1347981224_9499.png)

点击 HelloWorld 这个链接：

![](http://img.my.csdn.net/uploads/201209/18/1347981379_5225.png)

点击页面上的 Invoke 按钮：

![](http://img.my.csdn.net/uploads/201209/18/1347981471_5463.png)

然后我们改写这段代码，添加我们自己的方法进去：

![](http://img.my.csdn.net/uploads/201209/18/1347981611_2478.png)

**\[csharp]** [view plain](http://blog.csdn.net/yapingxin/article/details/7993989 "view plain")[copy](http://blog.csdn.net/yapingxin/article/details/7993989 "copy")[print](http://blog.csdn.net/yapingxin/article/details/7993989 "print")[?](http://blog.csdn.net/yapingxin/article/details/7993989 "?")

01. namespace WebApplication1
02. {
03. using System.Web.Services;
04. /// &lt;summary&gt;
05. /// Summary description for WebService1
06. /// &lt;/summary&gt;
07. \[WebService(Namespace = "http://tempuri.org/")]
08. public class WebService1 : System.Web.Services.WebService
09. {
10. \[WebMethod]
11. public string HelloWorld()
12. {
13. return "Hello World";
14. }
15. \[WebMethod]
16. public int Add(int x, int y)
17. {
18. return x + y;
19. }
20. }
21. }

运行：

![](http://img.my.csdn.net/uploads/201209/18/1347981852_3383.png)

点击 Add 链接，调用我们刚刚自己添加的 Add 函数：

![](http://img.my.csdn.net/uploads/201209/18/1347981997_2165.png)

点击页面上的 Invoke 按钮，得到以 XML 格式返回的执行结果：

![](http://img.my.csdn.net/uploads/201209/18/1347982223_4467.png)+

整个过程非常简单、直观。