WCF系列之.net(4.0) 在网站使用Js调用Wcf Rest

上一篇,我们介绍了如何使用JS去调用WCF。但实际开发中,各大网站的API都是REST风格,那我们也REST下,顺便用JS调用。

废话不多说,我就把几个比较重要的代码贴下:

接口:

using System.ServiceModel;
using System.ServiceModel.Web;
[ServiceContract]
public interface IproductService
{
    [WebGet(UriTemplate = "all", ResponseFormat = WebMessageFormat.Json)] //不设置这个 默认就是xml
    IEnumerable<Product> GetAll();
    [WebGet(UriTemplate="{id}")]
    Product Get(string id);
    [WebInvoke(UriTemplate="/",Method="POST")]
    void Create(Product product);
    [WebInvoke(UriTemplate = "/", Method = "PUT")]
    void Update(Product product);
    [WebInvoke(UriTemplate="/",Method="Delete")]
    void Detele(string id);

}

服务:

using System.ServiceModel.Activation;//这个告诉我们是否动态加载ServiceHost宿主
using System.ServiceModel; 


//要以IIS管道运行WCF服务 只需要加上这个特性就可以 运行网站的同时 运行WCF服务 AJAX也可以请求到了
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] //对象在每次调用前创建,在调用后回收
public class ProductService:IproductService
{
    public static IList<Product> products = new List<Product>()
    {
        new Product{Id="1",Department="IT部门",Name="Yuhao",Grade="软件开发"},
        new Product{Id="2",Department="IT部门",Name="Yuhao1",Grade="前端开发"}
    };

    #region IproductService 成员

    public IEnumerable<Product> GetAll()
    {
        return products;
    }

    public Product Get(string id)
    {
        Product product = products.FirstOrDefault(p => p.Id == id);
        if (null != product)
        {
            return product;
        }
        return null;
    }

    public void Create(Product product)
    {
        products.Add(product);
    }

    public void Update(Product product)
    {
        Product p = this.Get(product.Id);
        if (null != p)
        {
            products.Remove(p);
        }
        products.Add(product);

    }

    public void Detele(string id)
    {
        Product product = this.Get(id);
        if (null != product)
        {
            products.Remove(product);
        }

    }

    #endregion
}

webconfig:

    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"> <!--这里注册路由 直接拷贝过去就好 不需要wcf rest 模板 -->
            <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </modules>
    </system.webServer>

    <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
        <!--以asp.net 管道运行wcf rest 并且允许绑定到多个IIS上-->
        
        <standardEndpoints>
            <webHttpEndpoint>
                <!--编写REST的时候使用的配置-->
                <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> <!--helpEnabled 是否开启帮助 automaticFormatSelectionEnabled 是否启动自动格式-->
            </webHttpEndpoint>
        </standardEndpoints>
    </system.serviceModel>

注册路由:

    void Application_Start(object sender, EventArgs e) 
    {
        RegisterRoutes(); //注册路由
    }
    
    private void RegisterRoutes()
    {
        //把WCF rest 绑定到路由上
        System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute("ProductService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(ProductService)));
    }

好了,到此为主,是不是很简单,但这里是用的路由来帮助完成,所以下一篇,我就要说了现在流行的web api来做。
其实,我写这么多WCF服务,主要是告诉你 web api 是有多么简单,多好用,没有那么大配置和繁琐的地方。

示例代码下载:WcfDemo(.net4.0)Rest.JS.zip

原文地址:https://www.cnblogs.com/flyfish2012/p/2936750.html