ASP.NET 创建发布一个简单的wcf服务

ASP.NET创建WCF服务相对要比Winform或控制台要简单,如下:

1.在VS2010中,打开 “文件” --“新建” --“网站” --“Asp.net网站”,创建一个新的网站项目,系统将生成如下项目文件:

2. 右击项目--“添加新项”

3.选择“WCF服务”,输入服务名称

4.IDE将生成一些文件,如下:

我们可以看到生成了IServices.cs  Service.cs  Service.svc 以及修改了的Web.config

IServices.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService”。
[ServiceContract]
public interface IService
{
[OperationContract]
void DoWork();
}


Service.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service”。
public class Service : IService
{
public void DoWork()
{
}
}

Service.svc

(.SVC)是文件服务激活(File-Less Activation),作用类似于winform的宿主。

<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs"%>

Web.config增加了如下配置

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>


5.我们可以在类Service中做如下修改,修改返回类型为string 并且返回一个字符串:

public class Service : IService
{
public string DoWork()
{
return "HelloWord";
}
}

  我们在接口IService中公开契约,返回类型为string ,修改如下:

public interface IService
{
[OperationContract]
string DoWork();
}


6.发布站点,我们就可以使用http://服务器地址/Service.svc 访问WCF服务了。

  如本例的:http://localhost:49841/WebSite2/Service.svc,你看到如下页面

共同勉励,希望本文会对初学WCF的同学们有所帮助!



 

posted @ 2011-11-19 09:37  Yao,Mane  阅读(1220)  评论(0编辑  收藏  举报