微软动态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;
}