这是可能的。我假设您想在您的 ASP.NET Web 表单/mvc(无论)类型的项目中公开现有的 WCF 服务。
步骤:
1) 确保您的 ASP.NET 项目引用 WCF 服务实现所在的程序集
2) 将您的 ASP.NET 项目中的 global.asax 更改为:
using System.ServiceModel.Activation; // from assembly System.ServiceModel.Web
protected void Application_Start(Object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
routes.Add(new ServiceRoute("Services/Angular", new WebServiceHostFactory(), typeof(WCFNamespace.AngularService)));
}
这会注册以 /Service/Angular 前缀开头的调用,由您的 WCF 服务处理。
3) 您的 WCF 服务应如下所示
[ServiceContract]
public interface IAngularService
{
[OperationContract]
[WebGet(UriTemplate = "/Hello", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[Description("Returns hello world json object")]
HelloWorld GetHello();
}
[DataContract]
public class HelloWorld
{
[DataMember]
public string Message { get; set; }
}
注意这些方法——它们应该用[WebGet] 或[WebInvoke] 方法装饰,因为对于Angular,你想构建RESTfull wcf 服务。序列化/反序列化格式也设置为 json。
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class AngularService : IAngularService
{
public HelloWorld GetHello()
{
return new HelloWorld { Message = "Hello from WCF. Time is: " +
DateTime.Now.ToString() };
}
}
现在,如果您在浏览器中输入 /Services/Angular/Hello,您应该能够获取 json 对象。
最后,正如您所注意到的,WCF 合同实现(在本例中为类 AngularService)必须使用属性[AspNetCompatibilityRequirements] 进行标记,以便 IIS 可以将其托管在 ASP.NET Web 表单/MVC 项目下。
免责声明:这是非常幼稚的实现,在现实世界中,您可能希望捕获和记录服务中发生的异常,并将它们以 json 的形式返回给客户端。