如何在Dynamic CRM 2013中創建WebService接口供其它系統調用

由於MSCRM的異構性和封閉性,許多其它的平臺無法直接調用MSCRM提供的API接口,一般的處理方式是用.net編寫webservice,通過中間這一層轉換來使其它系統調用我們自己編寫的webservice.下面演示如何開發可調用MSCRM2013 API的webservice。

主要步驟:

  1. 新建asp.net web項目
  2. 編寫代碼
  3. 驗證服務
  4. 生成項目,並將相關文件拷貝到CRM的指定路徑

一.新建項目


右鍵點擊資源管理器項目,並添加一個web服務,此處名稱爲:MSCRMWebServiceDemo


引用相關的DLL文件



二.編寫代碼

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Description;
using System.Web;
using System.Web.Services;


namespace MSCRMWebServiceDemo
{
    /// <summary>
    /// MyMSCRMWebService 的摘要說明
    /// </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 MyMSCRMWebService : System.Web.Services.WebService
    {

        static private IOrganizationService GetOrganisationService()
        {
            ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = new NetworkCredential("crmadmin", "password01!", "test");

            OrganizationServiceProxy proxy = new OrganizationServiceProxy(new Uri("http://192.168.10.17/test/XRMServices/2011/Organization.svc"), null, credentials, null);

            return proxy as IOrganizationService;
        }

        [WebMethod]
        public string HelloWorld()
        {

            IOrganizationService service = GetOrganisationService();
           //用FETCHXML的方式獲取會員數據
            string fetch2 = @"
   <fetch mapping='logical'>
  <entity name='account'>
    <attribute name='name' />
    <attribute name='address1_city' />
    <attribute name='primarycontactid' />
    <attribute name='telephone1' />
    <attribute name='accountid' />
    <order attribute='name' descending='false' />
    <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
      <attribute name='emailaddress1' />
    </link-entity>
  </entity>
</fetch>";

            EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetch2));
            String name = "";

            foreach (var c in result.Entities)
            {
                name += c.Attributes["name"];
            }

            return name;
        }
    }
}
三.點擊VS的運行按鈕,測試服務




四.部署相關項目至CRM指定路徑

拷貝MSCRMWebServiceDemo.dll至CRM的以下路徑:

X:\Program Files\Microsoft Dynamics CRM\CRMWeb\bin

拷貝MyMSCRMWebService.asmx至CRM的以下路徑:

C:\Program Files\Microsoft Dynamics CRM\CRMWeb\ISV

最後驗證一下webservice,打開如下地址,出現以下界面則部署成功




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章