WebApi操作Dynamic数据

简单版本

using Microsoft.Ajax.Utilities;
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.Net.Http;
using System.ServiceModel.Description;
using System.Web.Http;
using System.Text;
namespace DynamicApiTest.Controllers
{
    public class ValuesController : ApiController
    {
        Uri orgServiceUri = new Uri("http://10.20.100.150:7777/Index/XRMServices/2011/Organization.svc");//组织服务地址
        ClientCredentials clientCredentials = new ClientCredentials();
        
        //连接dynamic的账号和密码
        public void run()
        {
            clientCredentials.Windows.ClientCredential = new NetworkCredential("lanhai", "P@ssw0rd", "LANHAI");
        }
        // GET api/values
        public EntityCollection Get()
        {
            run();
            using (OrganizationServiceProxy sev = new OrganizationServiceProxy(orgServiceUri, null, clientCredentials, null))
            {
                QueryExpression q = new QueryExpression("new_student");
                q.ColumnSet = new ColumnSet(true);
                EntityCollection ee = sev.RetrieveMultiple(q);
                StringBuilder sr = new StringBuilder();

                return ee;
            }
            
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

前端接收

<h2>Test</h2>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<div>
    <ul id="entityname">
       
    </ul>
</div>
<script>
    $.ajax({
        url: "/api/values",
        type: "get",
        dataType: "json",
        contentType: "application/json",
        success: function (data) {
           console.log(data);
        }, error: function (data) {
            console.log("lose");
        }

    })
</script>

 

将服务地址和登录账号、密码写入配置文件中

单独写一个servicehelper类来访问dynamic数据

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace DynamicApiTest.Models
{
    public class ServiceHelper
    {
        private static OrganizationServiceProxy organizationProxy { get; set; }


        public static OrganizationServiceProxy InitOrganizationProxy()
        {
            string _discoveryServiceAddress = ConfigurationManager.AppSettings["DiscoveryServiceAddress"];//获取组织服务地址
            IServiceManagement<IDiscoveryService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IDiscoveryService>(new Uri(_discoveryServiceAddress));
            AuthenticationProviderType endpointType = serviceManagement.AuthenticationType;

            AuthenticationCredentials authCredentials = GetCredentials(endpointType);

            string organizationUri = ConfigurationManager.AppSettings["DiscoveryServiceAddress"];
            if (!String.IsNullOrWhiteSpace(organizationUri))
            {
                IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri));

                AuthenticationCredentials credentials = GetCredentials(endpointType);

                return GetProxy<IOrganizationService, OrganizationServiceProxy>(orgServiceManagement, credentials);
            }
            else
                throw new Exception("未连接服务!");
        }

        private static AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType)
        {
            string _userName = ConfigurationManager.AppSettings["UserName"];
            string _password = ConfigurationManager.AppSettings["Password"];
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();
            switch (endpointType)
            {
                case AuthenticationProviderType.ActiveDirectory:
                    authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password);
                    break;
                case AuthenticationProviderType.Federation:
                case AuthenticationProviderType.OnlineFederation:
                    authCredentials.ClientCredentials.UserName.UserName = _userName;
                    authCredentials.ClientCredentials.UserName.Password = _password;
                    break;
                default:
                    break;
            }

            return authCredentials;
        }

        private static TProxy GetProxy<TService, TProxy>(IServiceManagement<TService> serviceManagement, AuthenticationCredentials authCredentials)
            where TService : class
            where TProxy : ServiceProxy<TService>
        {
            Type classType = typeof(TProxy);

            if (serviceManagement.AuthenticationType != AuthenticationProviderType.ActiveDirectory)
            {
                AuthenticationCredentials tokenCredentials = serviceManagement.Authenticate(authCredentials);
                return (TProxy)classType
                     .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(SecurityTokenResponse) })
                     .Invoke(new object[] { serviceManagement, tokenCredentials.SecurityTokenResponse });
            }

            return (TProxy)classType
                .GetConstructor(new Type[] { typeof(IServiceManagement<TService>), typeof(System.ServiceModel.Description.ClientCredentials) })
                .Invoke(new object[] { serviceManagement, authCredentials.ClientCredentials });
        }
    }
}

ResultDTD

public class ResultDTD
    {
        public int code { get; set; }
        public object data { get; set; }
    }

在api中访问dynamic数据,并返回一个json字符串

public IHttpActionResult Get()
        {
            using (OrganizationServiceProxy sev = ServiceHelper.InitOrganizationProxy())
            {
                //查询对应实体信息,返回一个json字符串
                string xml = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                    <entity name='tx_testentity_1'>
                                    <attribute name='tx_testentity_1id' />
                                    <attribute name='tx_name' />
                                    <attribute name='createdon' />
                                    <order attribute='tx_name' descending='false' />
                                  </entity>
                                </fetch>";
                var fetch = new FetchExpression(xml);
                EntityCollection response = sev.RetrieveMultiple(fetch);//获取实体信息
                ResultDTD result = new ResultDTD();//返回的数据类
                result.code = 200;//状态码
                if (response.Entities.Count > 0)
                {
                    result.data = response.Entities.Select(x => new new_testentiyt_1//根据查询到的数据封装的一个类
                    {
                        new_name = x.GetAttributeValue<string>("tx_name")//fetch查询到的数据
                    });
                }
                //将json字符串转化为list集合
                //string value = JsonConvert.SerializeObject(result.data);
                //ls = JsonConvert.DeserializeObject<List<类名称>>(value);
                
                
                
                return Json(result);
            }

        }

//返回结果

 

跨域设置

 

origins:允许访问的域名,多个域名以逗号分隔。使用“*”全部允许。

headers:配置所支持的资源,使用“*”全部允许,使用null或“”不允许。

methods:配置支持的请求方法,使用“*”全部允许,使用null或“”不允许。

原文地址:https://www.cnblogs.com/LanHai12/p/15258006.html