Özel bağlayıcıda özel kod kullanma

Özel kod, istek ve yanıt yüklerini varolan ilke şablonlarının kapsamı ötesinde dönüştürür. Kod kullandığınızda, kodsuz tanımdan önceliklidir.

Daha fazla bilgi için bkz. Sıfırdan özel bağlayıcı oluşturma.

Komut dosyası sınıfı

Kodunuzun, çalışma zamanında çalışan ExecuteAsync adlı bir yöntemi uygulaması gerekir. Gerektiğinde bu sınıfta başka yöntemler oluşturabilir ve bunları yönteminden ExecuteAsync çağırabilirsiniz. Sınıf adı Script olmalıdır ve ScriptBase gerçeklemelidir.

public class Script : ScriptBase
{
    public override Task<HttpResponseMessage> ExecuteAsync()
    {
        // Your code here
    }
}

Destekleyici sınıfların ve arabirimlerin tanımı

sınıfı Script aşağıdaki sınıflara ve arabirimlere başvurur. Bunları yerel test ve derleme için kullanın.

public abstract class ScriptBase
{
    // Context object
    public IScriptContext Context { get; }

    // CancellationToken for the execution
    public CancellationToken CancellationToken { get; }

    // Helper: Creates a StringContent object from the serialized JSON
    public static StringContent CreateJsonContent(string serializedJson);

    // Abstract method for your code
    public abstract Task<HttpResponseMessage> ExecuteAsync();
}

public interface IScriptContext
{
    // Correlation Id
    string CorrelationId { get; }

    // Connector Operation Id
    string OperationId { get; }

    // Incoming request
    HttpRequestMessage Request { get; }

    // Logger instance
    ILogger Logger { get; }

    // Used to send an HTTP request
    // Use this method to send requests instead of HttpClient.SendAsync
    Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken);
}

Örnekler

Merhaba Dünya betiği

Bu örnek betik her zaman tüm istekler için yanıt olarak Merhaba Dünya döndürür.

public override async Task<HttpResponseMessage> ExecuteAsync()
{
    // Create a new response
    var response = new HttpResponseMessage();

    // Set the content
    // Initialize a new JObject and call .ToString() to get the serialized JSON
    response.Content = CreateJsonContent(new JObject
    {
        ["greeting"] = "Hello World!",
    }.ToString());

    return response;
}

Regex betiği

Aşağıdaki örnek, eşleştirilecek bir metin ve düzenli ifade alır ve yanıtta eşleşme sonucunu döndürür.

public override async Task<HttpResponseMessage> ExecuteAsync()
{
    // Check if the operation ID matches what is specified in the OpenAPI definition of the connector
    if (this.Context.OperationId == "RegexIsMatch")
    {
        return await this.HandleRegexIsMatchOperation().ConfigureAwait(false);
    }

    // Handle an invalid operation ID
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
    response.Content = CreateJsonContent($"Unknown operation ID '{this.Context.OperationId}'");
    return response;
}

private async Task<HttpResponseMessage> HandleRegexIsMatchOperation()
{
    HttpResponseMessage response;

    // We assume the body of the incoming request looks like this:
    // {
    //   "textToCheck": "<some text>",
    //   "regex": "<some regex pattern>"
    // }
    var contentAsString = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);

    // Parse as JSON object
    var contentAsJson = JObject.Parse(contentAsString);

    // Get the value of text to check
    var textToCheck = (string)contentAsJson["textToCheck"];

    // Create a regex based on the request content
    var regexInput = (string)contentAsJson["regex"];
    var rx = new Regex(regexInput);

    JObject output = new JObject
    {
        ["textToCheck"] = textToCheck,
        ["isMatch"] = rx.IsMatch(textToCheck),
    };

    response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = CreateJsonContent(output.ToString());
    return response;
}

İletme betiği

Aşağıdaki örnek, gelen isteği arka uca iletir.

public override async Task<HttpResponseMessage> ExecuteAsync()
{
    // Check if the operation ID matches what is specified in the OpenAPI definition of the connector
    if (this.Context.OperationId == "ForwardAsPostRequest")
    {
        return await this.HandleForwardOperation().ConfigureAwait(false);
    }

    // Handle an invalid operation ID
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
    response.Content = CreateJsonContent($"Unknown operation ID '{this.Context.OperationId}'");
    return response;
}

private async Task<HttpResponseMessage> HandleForwardOperation()
{
    // Example case: If your OpenAPI definition defines the operation as 'GET', but the backend API expects a 'POST',
    // use this script to change the HTTP method.
    this.Context.Request.Method = HttpMethod.Post;

    // Use the context to forward/send an HTTP request
    HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(continueOnCapturedContext: false);
    return response;
}

İletme ve dönüştür betiği

Aşağıdaki örnek gelen isteği iletir ve arka uçtan döndürülen yanıtı dönüştürür.

public override async Task<HttpResponseMessage> ExecuteAsync()
{
    // Check if the operation ID matches what is specified in the OpenAPI definition of the connector
    if (this.Context.OperationId == "ForwardAndTransformRequest")
    {
        return await this.HandleForwardAndTransformOperation().ConfigureAwait(false);
    }

    // Handle an invalid operation ID
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.BadRequest);
    response.Content = CreateJsonContent($"Unknown operation ID '{this.Context.OperationId}'");
    return response;
}

private async Task<HttpResponseMessage> HandleForwardAndTransformOperation()
{
    // Use the context to forward/send an HTTP request
    HttpResponseMessage response = await this.Context.SendAsync(this.Context.Request, this.CancellationToken).ConfigureAwait(continueOnCapturedContext: false);

    // Do the transformation if the response was successful, otherwise return error responses as-is
    if (response.IsSuccessStatusCode)
    {
        var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
        
        // Example case: response string is some JSON object
        var result = JObject.Parse(responseString);
        
        // Wrap the original JSON object into a new JSON object with just one key ('wrapped')
        var newResult = new JObject
        {
            ["wrapped"] = result,
        };
        
        response.Content = CreateJsonContent(newResult.ToString());
    }

    return response;
}

Desteklenen ad alanları

Tüm C# ad alanları desteklenmez. Şu anda, işlevleri yalnızca aşağıdaki ad alanlarından kullanabilirsiniz.

Önemli

Şu anda desteklenen .NET sürümü .NET Standard 2.0'dır.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

GitHub örnekleri

DocuSign bağlayıcısındaki örnekler için, GitHub'da Power Platform Bağlayıcıları'na gidin.

Özel kodla ilgili SSS

Özel kod hakkında daha fazla bilgi edinmek için bkz . 4. Adım: (İsteğe bağlı) Özel kod desteği kullanma.

S: Özel bağlayıcı başına birden çok betik kullanabilir miyim?Y: Hayır, özel bağlayıcı başına yalnızca bir betik dosyası kullanabilirsiniz.

S: Özel bağlayıcımı güncelleştirirken iç sunucu hatası alıyorum. Sorun ne olabilir? Y: Büyük olasılıkla kodunuzu derlerken bir sorun vardır. Gelecekte sistem, bu deneyimi geliştirmek için derleme hatalarının tam listesini görüntüler. Şimdilik, geçici bir çözüm olarak derleme hatalarını yerel olarak test etmek için destekleyici sınıfları kullanın.

S: Koduma günlük kaydı ekleyebilir ve hata ayıklama için bir izleme alabilir miyim?Y: Şu anda değil, ancak gelecekte bu özellik için destek eklenecektir.

S: Bu arada kodumu nasıl test ederim?Y: Yerel olarak test edin ve yalnızca desteklenen ad alanları içinde sağlanan ad alanlarını kullanarak kod derleyebileceğinizden emin olun. Yerel test hakkında bilgi için bkz. Özel bağlayıcıda kod yazma.

S: Herhangi bir sınır var mı?Y: Evet, evet. Komut dosyanızın çalışması 2 dakika içinde tamamlanmalı ve komut dosyanızın boyutu 1 MB'ı geçmemelidir. Bu yeni 2 dakikalık zaman aşımı, yeni oluşturulan tüm özel bağlayıcılar için geçerlidir. Mevcut özel bağlayıcılar için, yeni zaman aşımını uygulamak için bağlayıcıyı güncelleştirmeniz gerekir.

S: Betik kodunda kendi HTTP istemcimi oluşturabilir miyim?Y: Şu anda evet, ancak sistem gelecekte bu özelliği engeller. Önerilen yöntem, this.Context.SendAsync yöntemini kullanmaktır.

S: Şirket içi veri ağ geçidiyle özel kod kullanabilir miyim?Y: Şu anda yok, hayır.

Sanal Ağ desteği

Bağlayıcıyı sanal ağa bağlı bir Power Platform ortamında kullandığınızda, aşağıdaki sınırlamalar geçerlidir:

  • Context.SendAsync genel uç nokta kullandığından sanal ağdaki özel uç noktalardan verilere erişemez.

Genel sınırlamalar ve bilinen sorunlar

Bazı bölgelerde OperationId üst bilgi base64 kodlanmış biçiminde döndürülüyor. Uygulamanız OperationId değerini gerektiriyorsa, kullanmak için bunun base64 kodunu çözün.

public override async Task<HttpResponseMessage> ExecuteAsync()
{
    string realOperationId = this.Context.OperationId;
    // Resolve potential issue with base64 encoding of the OperationId
    // Test and decode if it's base64 encoded
    try {
        byte[] data = Convert.FromBase64String(this.Context.OperationId);
        realOperationId = System.Text.Encoding.UTF8.GetString(data);
    }
    catch (FormatException ex) {}
    // Check if the operation ID matches what is specified in the OpenAPI definition of the connector
    if (realOperationId == "RegexIsMatch")
    // Refer to the original examples above for remaining details
}

Sonraki adım

Sıfırdan özel bağlayıcı oluşturma

Geri bildirimde bulunun

Bağlayıcı platformumuzla veya yeni özellik fikirlerimizle ilgili sorunlar hakkındaki geri bildirimleriniz bizim için çok önemlidir. Geri bildirimde bulunmak için Sorun gönderme veya bağlayıcılarla ilgili yardım alma bölümüne gidip geri bildirim türünü seçin.