Visual Studio 2010默认采用的框架为.NET Framework4,在这个框架中已找不到直接建立WebService的模板方式了。但VS2010能够建立WebService是毋庸置疑的,那么怎么在VS2010中建立WebService呢,请看下面为您提供的两种方法,方法已经本人测试,能够放心使用!web
方法一:.NET Framework4.0框架下,依然能够建立WebService,步骤以下:浏览器
① 选择"ASP.NET空Web应用程序<ASP.NET Empty Web Application>"模板,创建空的网站or项目; 框架
② 添加新项,在"添加新项"窗口中,会找到WebService这个项目模板。函数
方法二:将VS2010采用的默认框架,改成使用框架.NET Framework2.0\3.0\3.5,这时新建"项目"or新建"网站"就能够找到须要的"ASP.NET WebService模板"来创建WebService了。测试
采用.NET2.0\3.0\3.5建立完WebService,若是这时须要使用.NET Framework4.0的新特性,可在项目属性窗口or网站属性窗口的Build选项卡中选择.NET Framework4.0.网站
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;ui
namespace WebServiceTwo
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[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
{spa
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}orm
} }
在代码文件里,若是咱们写了一个函数后,但愿此函数成为外部可调用的接口函数,咱们必须在函数上面添上一行代码[WebMethod(Description="函数的描述信息")],若是你的函数没有这个申明,它将不能被用户引用.下来咱们开始编写一个简单的Web Service 的例子。接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebServiceTwo
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[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]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(Description = "求和的方法")]
public double addition(double i, double j)
{ return i + j; }
[WebMethod(Description = "求差的方法")]
public double subtract(double i, double j)
{ return i - j; }
[WebMethod(Description = "求积的方法")]
public double multiplication(double i, double j)
{ return i * j; }
[WebMethod(Description = "求商的方法")]
public double division(double i, double j)
{
if (j != 0)
return i / j;
else
return 0;
}
}
}
错误缘由,默认WebServise的类的类名是Service1,下面实例化时须要实例化这个类,若是不是就会报错请注意<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" class="Service" % >里的Class="Service1",则Service1必须是你下面定义的类名,若是用其它类名则会有错误