(转)在 Visual Studio 2010 中创建 ASP.Net Web Service

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

 

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

 

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

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

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

 

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

 

好,我们继续:

 

第三步:编码、运行

 

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

 

[csharp] view plain copy print ?
 
  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Web.Services;
  6. namespacesitedemo.Services
  7. {
  8. ///<summary>
  9. ///SummarydescriptionforCalculateService
  10. ///</summary>
  11. [WebService(Namespace="http://tempuri.org/")]
  12. [WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
  13. [System.ComponentModel.ToolboxItem(false)]
  14. //ToallowthisWebServicetobecalledfromscript,usingASP.NETAJAX,uncommentthefollowingline.
  15. //[System.Web.Script.Services.ScriptService]
  16. publicclassCalculateService:System.Web.Services.WebService
  17. {
  18. [WebMethod]
  19. publicstringHelloWorld()
  20. {
  21. return"HelloWorld";
  22. }
  23. }
  24. }


直接Press F5就可以看到结果:

 

 

 

 

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

 

[csharp] view plain copy print ?
 
  1. usingSystem.Web.Services;
  2. namespacesitedemo.Services
  3. {
  4. ///<summary>
  5. ///SummarydescriptionforCalculateService
  6. ///</summary>
  7. [WebService(Namespace="http://tempuri.org/")]
  8. publicclassCalculateService:WebService
  9. {
  10. [WebMethod]
  11. publicstringHelloWorld()
  12. {
  13. return"HelloWorld";
  14. }
  15. [WebMethod]
  16. publicintAdd(intx,inty)
  17. {
  18. returnx+y;
  19. }
  20. }
  21. }


运行:

 

 

 

 

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

 

 

总结

现在我们再回过头来看看,从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,这才是最合理的作法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值