微软动态CRM专家罗勇 ,回复325或者20190428可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!

现在Web API越来越流行,有时候为了程序更加健壮,需要在插件/自定义工作流活动中调用Web API,请求数据内容和返回数据内容都是JSON格式,我这里准备了一些代码示例,方便以后参考,也欢迎各位读者提供建议,我的C#水平有限,望各位不吝赐教。

插件代码示例:

using System;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks; namespace Plugins
{
public class PreAccountCreate : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Enter PreAccountCreate on {0}", DateTime.Now.ToString());
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity currentEntity = (Entity)context.InputParameters["Target"];
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
string requestJson = string.Empty;
var request = new GetTeamMembersRequest()
{
TeamName = "Thomas Luo",
WordConnector = ";"
};
var serializer = new DataContractJsonSerializer(typeof(GetTeamMembersRequest));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, request);
requestJson = Encoding.UTF8.GetString(ms.ToArray());
}
tracingService.Trace("HTTP POST REQUEST BODY = {0}", requestJson);
var responseContent = PostApiAsync(requestJson).Result;
tracingService.Trace("HTTP POST RESPONSE CONTENT = {0}", responseContent);
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseContent)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(GetTeamMembersResponse));
GetTeamMembersResponse repsonse = (GetTeamMembersResponse)deseralizer.ReadObject(ms);
//这里就是调用返回内容
//throw new InvalidPluginExecutionException(repsonse.UserEmailAddrs + repsonse.UserFullName + repsonse.UserIds);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in PreAccountCreate.", ex);
}
catch (Exception ex)
{
tracingService.Trace("PreAccountCreate unexpected exception: {0}", ex.Message);
throw;
}
}
tracingService.Trace("Leave PreAccountCreate on {0}", DateTime.Now.ToString());
} private async Task<string> PostApiAsync(string requestJson)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(@"https://thomaswebapi.azurewebsites.net/api/CustomerEngagement", content).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}
} public class GetTeamMembersRequest
{
public string TeamName { get; set; } public string WordConnector { get; set; }
} public class GetTeamMembersResponse
{
public string UserIds { get; set; } public string UserEmailAddrs { get; set; } public string UserFullName { get; set; } public string ResultCode { get; set; } public string ResultDesc { get; set; }
}
}

自定义工作流活动代码示例:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using System;
using System.Activities;
using System.IO;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks; namespace Flows
{
public class InvokeWebApi : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
ITracingService tracingService = executionContext.GetExtension<ITracingService>();
tracingService.Trace("Enter InvokeWebApi on {0}", DateTime.Now.ToString());
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);
try
{
string requestJson = string.Empty;
var request = new GetTeamMembersRequest()
{
TeamName = "Thomas Luo",
WordConnector = ";"
};
var serializer = new DataContractJsonSerializer(typeof(GetTeamMembersRequest));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, request);
requestJson = Encoding.UTF8.GetString(ms.ToArray());
}
tracingService.Trace("HTTP POST REQUEST BODY = {0}", requestJson);
var responseContent = PostApiAsync(requestJson).Result;
tracingService.Trace("HTTP POST RESPONSE CONTENT = {0}", responseContent);
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(responseContent)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(GetTeamMembersResponse));
GetTeamMembersResponse repsonse = (GetTeamMembersResponse)deseralizer.ReadObject(ms);
//这里就是调用返回内容
//throw new InvalidPluginExecutionException(repsonse.UserEmailAddrs + repsonse.UserFullName + repsonse.UserIds);
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in InvokeWebApi.", ex);
}
catch (Exception ex)
{
tracingService.Trace("InvokeWebApi unexpected exception: {0}", ex.Message);
throw;
}
tracingService.Trace("Leave InvokeWebApi on {0}", DateTime.Now.ToString());
} private async Task<string> PostApiAsync(string requestJson)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
var content = new StringContent(requestJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(@"https://thomaswebapi.azurewebsites.net/api/CustomerEngagement", content).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}
} public class GetTeamMembersRequest
{
public string TeamName { get; set; } public string WordConnector { get; set; }
} public class GetTeamMembersResponse
{
public string UserIds { get; set; } public string UserEmailAddrs { get; set; } public string UserFullName { get; set; } public string ResultCode { get; set; } public string ResultDesc { get; set; }
}
}

当然若你使用HTTP GET,参考下面的示例:

        private async Task<string> GetApiAsync(string OrderNumber)
{
string returnVal = string.Empty;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(string.Format("https://thomaswebapi.azurewebsites.net/api/Order?OrderNo={0}",OrderNumber)).Result;
if (response.IsSuccessStatusCode)
{
returnVal = await response.Content.ReadAsStringAsync();
}
else
{
throw new InvalidPluginExecutionException(response.Content.ReadAsStringAsync().Result);
}
}
return returnVal;
}

Dynamics 365 CE的插件/自定义工作流活动中调用Web API示例代码的更多相关文章

  1. 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API

    微软动态CRM专家罗勇 ,回复337或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 配置Dynamics 365 & PowerApps 支 ...

  2. Dynamics 365中自定义工作流活动获取的上下文分析及注意事项

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复244或者20170306可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  3. Dynamics 365中自定义工作流活动更新了输入输出参数后获取的方法

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复245或者20170309可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  4. Dynamics CRM模拟OAuth请求获得Token后在外部调用Web API

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复233或者20161104可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  5. Dynamics 365 CE将自定义工作流活动程序集注册到磁盘并引用其他类库

    我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

  6. 自定义工作流活动报错:您无法登陆系统。原因可能是您的用户记录或您所属的业务部门在Microsoft Dynamics 365中已被禁用。

    本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复265或者20170926可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...

  7. 自定义工作流活动运行产生System.Security.SecurityException

    摘要: 微软动态CRM专家罗勇 ,回复305或者20190224可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me!我的网站是 www.luoyong.me . 最近碰到一个 ...

  8. Dynamics 365 CE Update消息PostOperation阶段Image的尝试

    我是微软Dynamics 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

  9. 使用Dynamics 365 CE Web API查询数据加点料及选项集字段常用查询

    微软动态CRM专家罗勇 ,回复336或者20190516可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 紧接上文:配置Postman通过OAuth 2 implicit ...

随机推荐

  1. 写XML

    //创XML建对象 XmlDocument doc = new XmlDocument(); //bool a = false; //声明根节点 XmlElement books; //判断文件是否存 ...

  2. Python_自定义有向图

    directedGraph.py class DirectedGraph(object): def __init__(self,d): if isinstance(d,dict): self.__gr ...

  3. 在AspNetCore 中 使用Redis实现分布式缓存

    AspNetCore 使用Redis实现分布式缓存 上一篇讲到了,Core的内置缓存:IMemoryCache,以及缓存的基础概念.本篇会进行一些概念上的补充. 本篇我们记录的内容是怎么在Core中使 ...

  4. Swagger使用教程大全,从入门到精通

    Swagger是遵守OpenAPI规范(OAS)的世界上最大的API框架开发工具,可在整个API生命周期内进行开发,从设计和文档到测试和部署.它提供了许多试用的工具来帮助开发者进行接口开发,如及时接口 ...

  5. 深入NGINX:nginx高性能的实现原理

    深入NGINX:我们如何设计它的性能和扩展性 来源: cnBeta  原文链接 英文原文:Inside NGINX: How We Designed for Performance & Sca ...

  6. 基于.net core实现项目自动编译、并生成nuget包

    近期想对自己的项目增加自动编译并生成nuget包,网上资料不少.但总还有迷糊的时候.首先:此解决方案包含多种版本的项目,如:有编译必须是x86平台,以及还有传统的.net foramework项目,以 ...

  7. java基础之接口(抽象类与接口的区别)

    概述 猫狗案例,我们想想狗一般就是看门,猫一般就是作为宠物了,对不.但是,现在有很多的驯养员或者是驯的,这应该属于经过特殊的培训训练出来的,对不.所以,这些额外的动作定义到动物类中就不合适,也不适合直 ...

  8. 【转】一则使用WinDbg工具调试iis进程调查内存占用过高的案例

    最近遇到一个奇葩内存问题,跟了三四天,把Windbg玩熟了,所以打算分享下. 症状简介 我们团队的DEV开发环境只有一台4核16G的win2012r2.这台服务器上装了SqlServer.TFS(项目 ...

  9. BZOJ_1877_[SDOI2009]晨跑_费用流

    BZOJ_1877_[SDOI2009]晨跑_费用流 题意: Elaxia最近迷恋上了空手道,他为自己设定了一套健身计划,比如俯卧撑.仰卧起坐等 等,不过到目前为止,他 坚持下来的只有晨跑. 现在给出 ...

  10. 这么用Mac才叫爽!

    用了近一年的 Macbook Pro,已经离不开它了.真是生活工作学习必备之良品啊. 如果你将要买苹果电脑或者刚买,那么不妨看看此文.推荐一些个人觉得好用的软件,而Mac本身的使用技巧----触控板. ...