C# vs2010中如何建立webservice

转自:http://blog.csdn.net/yapingxin/article/details/7331375 api


不少人在论坛里说,在Visual Studio 2010中不能建立“ASP.Net Web Service”这种project了,下面跟帖者云云,有的说这是由于微软已经将Web Service整合进WCF,也有的提出一种先将.Net Framework Target设置为3.5的一种很“Tricky”的做法,其实这些说法是不许确的。微软确实用WCF整合了Web Service,但并不等于说微软不许备让你们在Visual Studio里面建立传统的Web Service了。其实正确的作法很简单,你们一看就恍然大悟了。ide


第一步:建立一个“ASP.Net Empty Web Application”项目this



第二步:在项目中添加“Web Service”新项目编码

第一步以后,Visual Studio 2010会建立一个仅含一个站点配制文件(Web.config)的空站点,其他的什么也没有。
spa

咱们在Visual Studio 2010的Solution Explorer中,选中当前的这个project,添加新项目(右键菜单:Add --> New Item),选择“Web Service”这种类型:.net


看到这里读者应该就恍然大悟了吧。orm


好,咱们继续:blog


第三步:编码、运行教程


添加完Web Service这种new item以后,Visual Studio已经替咱们写了个示范的Web方法了:ip


[csharp] view plaincopyprint?

  1. using System;  

  2. using System.Collections.Generic;  

  3. using System.Linq;  

  4. using System.Web;  

  5. using System.Web.Services;  

  6.   

  7. namespace sitedemo.Services  

  8. {  

  9.     /// <summary>  

  10.     /// Summary description for CalculateService  

  11.     /// </summary>  

  12.     [WebService(Namespace = "http://tempuri.org/")]  

  13.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  

  14.     [System.ComponentModel.ToolboxItem(false)]  

  15.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   

  16.     // [System.Web.Script.Services.ScriptService]  

  17.     public class CalculateService : System.Web.Services.WebService  

  18.     {  

  19.   

  20.         [WebMethod]  

  21.         public string HelloWorld()  

  22.         {  

  23.             return "Hello World";  

  24.         }  

  25.     }  

  26. }  


直接Press F5就能够看到结果:





而后咱们改写这段代码,添加咱们本身的方法进去:


[csharp] view plaincopyprint?

  1. using System.Web.Services;  

  2.   

  3. namespace sitedemo.Services  

  4. {  

  5.     /// <summary>  

  6.     /// Summary description for CalculateService  

  7.     /// </summary>  

  8.     [WebService(Namespace = "http://tempuri.org/")]  

  9.     public class CalculateService : WebService  

  10.     {  

  11.         [WebMethod]  

  12.         public string HelloWorld()  

  13.         {  

  14.             return "Hello World";  

  15.         }  

  16.   

  17.         [WebMethod]  

  18.         public int Add(int x, int y)  

  19.         {  

  20.             return x + y;  

  21.         }  

  22.     }  

  23. }  


运行:





怎么样,是否是很简单?微笑



总结

如今咱们再回过头来看看,从VS2010以前版本的旧的建立Web Service的方式,到如今新的变化,Visual Studio改动了什么?

手头的机器没有装旧版的Visual Studio,我就现从网上抓一张教程里的截图吧,让咱们看看旧版的Visual Studio里面你们建立Web Service时建立新项目的截图:


不少人说在Visual Studio 2010里面没法建立Web Service,他们大概是在寻找上面截图中的这种“ASP.Net Web Service”项目吧。

如今再回过头来看看,其实微软在Visual Studio 2010里面做了一个至关合理(make sense)的改变。

Web Service并不能单独存在,它必须Host在一个Web Site/Web Application上面。因此,在一个Web Site/Web Application里面,经过Add new item添加一个Web Service,这才是最合理的做法。

相关文章
相关标签/搜索