Azure Functions C# 스크립트(.csx) 개발자 참조

이 문서는 C# 스크립트(.csx)를 사용하여 Azure Functions를 개발하는 방법을 소개합니다.

Important

C# 스크립트는 C# 함수를 빠르게 만들고 실행하는 데 도움이 되는 편리한 포털 내 환경을 제공하기 위해 주로 지원됩니다. 프로덕션 품질 앱의 경우 C# 함수를 컴파일된 C# 클래스 라이브러리 프로젝트로 로컬로 개발해야 합니다. C# 스크립트 프로젝트를 C# 클래스 라이브러리(격리된 작업자) 프로젝트로 마이그레이션하는 방법을 알아보려면 C# 스크립트 앱을 C# 프로젝트로 변환을 참조하세요.

Azure Functions를 사용하면 다음 방법 중 하나로 C#을 사용하여 함수를 개발할 수 있습니다.

Type 실행 프로세스 코드 확장자 개발 환경 참조
C# 스크립트 In Process .csx 포털
핵심 도구
이 문서의 내용
C# 클래스 라이브러리(격리된 작업자) 격리된 작업자 프로세스 .cs Visual Studio
Visual Studio Code
핵심 도구
.NET 격리 작업자 프로세스 함수
C# 클래스 라이브러리(In Process) In Process .cs Visual Studio
Visual Studio Code
핵심 도구
진행 중인 C# 클래스 라이브러리 함수

.csx의 작동 원리

데이터는 메서드 인수를 통해 C# 함수로 흐릅니다. 인수 이름은 function.json 파일에 지정되며 함수 로거 및 취소 토큰 같은 항목에 액세스하기 위해 미리 정의된 이름이 있습니다.

.csx 형식을 사용하면 "상용구"를 덜 작성하고 C# 함수를 작성하는 데 집중할 수 있습니다. 네임스페이스 및 클래스의 모든 항목을 래핑하는 대신 Run 메서드만 정의합니다. 일반적으로 파일의 시작 부분에 모든 어셈블리 참조 및 네임스페이스를 포함합니다.

함수 앱의 .csx 파일은 인스턴스가 초기화될 때 컴파일됩니다. 이 컴파일 단계는 콜드 시작 등의 방식이 C# 클래스 라이브러리에 비해 C# 스크립트 함수를 실행하는 데 더 오래 걸릴 수 있음을 의미합니다. 이 컴파일 단계는 C# 스크립트 함수가 C# 클래스 라이브러리와 달리 Azure Portal에서 편집 가능한 이유를 나타내기도 합니다.

폴더 구조

C# 스크립트 프로젝트의 폴더 구조는 다음 예와 같습니다.

FunctionsProject
 | - MyFirstFunction
 | | - run.csx
 | | - function.json
 | | - function.proj
 | - MySecondFunction
 | | - run.csx
 | | - function.json
 | | - function.proj
 | - host.json
 | - extensions.csproj
 | - bin

함수 앱을 구성하는 데 사용할 수 있는 공유 host.json 파일이 있습니다. 각 함수에는 자체 코드 파일(.csx)과 바인딩 구성 파일(function.json)이 있습니다.

Functions 런타임의 버전 2.x 이상 버전에 필요한 바인딩 확장은 extensions.csproj 파일에 정의되어 있고 실제 라이브러리 파일은 bin 폴더에 있습니다. 로컬에서 개발할 때는 바인딩 확장을 등록해야 합니다. Azure Portal에서 함수를 개발할 때 이 등록이 자동으로 수행됩니다.

인수에 바인딩

입력 또는 출력 데이터는 function.json 구성 파일의 name 속성을 통해 C# 스크립트 함수 매개 변수에 바인딩됩니다. 다음 예제에서는 큐 트리거 함수에 대한 function.json 파일 및 run.csx 파일을 보여 줍니다. 큐 메시지에서 데이터를 받는 매개 변수 이름은 name 속성의 값이기 때문에 myQueueItem으로 지정됩니다.

{
    "disabled": false,
    "bindings": [
        {
            "type": "queueTrigger",
            "direction": "in",
            "name": "myQueueItem",
            "queueName": "myqueue-items",
            "connection":"MyStorageConnectionAppSetting"
        }
    ]
}
#r "Microsoft.WindowsAzure.Storage"

using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using System;

public static void Run(CloudQueueMessage myQueueItem, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem.AsString}");
}

#r 문은 이 문서 뒷부분에 설명되어 있습니다.

바인딩에 대해 지원되는 형식

각 바인딩에는 자체적인 지원 형식이 있습니다. 예를들 어, Blob 트리거는 문자열 매개 변수, POCO 매개 변수, CloudBlockBlob 매개 변수 또는 지원되는 기타 몇 가지 형식과 함께 사용될 수 있습니다. Blob 바인딩에 대한 바인딩 참조 문서에는 Blob 트리거에 대해 지원되는 모든 매개 변수 형식이 나와 있습니다. 자세한 내용은 트리거 및 바인딩각 바인딩 형식에 대한 바인딩 참조 문서를 참조하세요.

HTTP 또는 WebHook를 사용할 계획인 경우 HttpClient의 부적절한 인스턴스화로 인해 발생할 수 있는 포트 소모를 피하도록 계획합니다. 자세한 내용은 Azure Functions에서 연결을 관리하는 방법을 참조하세요.

사용자 지정 클래스 참조

사용자 지정 POCO(Plain Old CLR Object) 클래스를 사용해야 하는 경우 동일한 파일 내에 클래스 정의를 포함하거나 별도 파일에 추가할 수 있습니다.

다음 예제에서는 POCO 클래스 정의를 포함하는 run.csx 예를 보여 줍니다.

public static void Run(string myBlob, out MyClass myQueueItem)
{
    log.Verbose($"C# Blob trigger function processed: {myBlob}");
    myQueueItem = new MyClass() { Id = "myid" };
}

public class MyClass
{
    public string Id { get; set; }
}

POCO 클래스에는 각 속성에 대해 정의된 Getter 및 setter가 있어야 합니다.

.csx 코드 재사용

run.csx 파일에 있는 다른 .csx 파일에 정의된 클래스와 메서드를 사용할 수 있습니다. 이를 위해 run.csx 파일의 #load 지시문을 사용합니다. 다음 예제에서는 MyLogger이라는 이름의 로깅 루틴이 myLogger.csx에서 공유되고 #load 지시문을 사용하여 run.csx로 로드됩니다.

예제 run.csx:

#load "mylogger.csx"

using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"Log by run.csx: {DateTime.Now}");
    MyLogger(log, $"Log by MyLogger: {DateTime.Now}");
}

예제 mylogger.csx:

public static void MyLogger(ILogger log, string logtext)
{
    log.LogInformation(logtext);
}

공유된 .csx 파일을 사용하는 것은 POCO 개체를 사용하여 함수 간에 전달된 데이터에 강력한 형식을 지정하려는 경우에 일반적인 패턴입니다. 다음 간단한 예제에서는 HTTP 트리거 및 큐 트리거는 Order라는 이름의 POCO 개체를 공유하여 주문 데이터를 강력한 형식으로 만듭니다.

HTTP 트리거를 위한 run.csx 예제:

#load "..\shared\order.csx"

using System.Net;
using Microsoft.Extensions.Logging;

public static async Task<HttpResponseMessage> Run(Order req, IAsyncCollector<Order> outputQueueItem, ILogger log)
{
    log.LogInformation("C# HTTP trigger function received an order.");
    log.LogInformation(req.ToString());
    log.LogInformation("Submitting to processing queue.");

    if (req.orderId == null)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
    else
    {
        await outputQueueItem.AddAsync(req);
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

큐 트리거를 위한 run.csx 예제:

#load "..\shared\order.csx"

using System;
using Microsoft.Extensions.Logging;

public static void Run(Order myQueueItem, out Order outputQueueItem, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed order...");
    log.LogInformation(myQueueItem.ToString());

    outputQueueItem = myQueueItem;
}

order.csx 예제:

public class Order
{
    public string orderId {get; set; }
    public string custName {get; set;}
    public string custAddress {get; set;}
    public string custEmail {get; set;}
    public string cartId {get; set; }

    public override String ToString()
    {
        return "\n{\n\torderId : " + orderId +
                  "\n\tcustName : " + custName +
                  "\n\tcustAddress : " + custAddress +
                  "\n\tcustEmail : " + custEmail +
                  "\n\tcartId : " + cartId + "\n}";
    }
}

#load 지시문으로 상대 경로를 사용할 수 있습니다.

  • #load "mylogger.csx" 는 함수 폴더에 있는 파일을 로드합니다.
  • #load "loadedfiles\mylogger.csx" 는 함수 폴더의 폴더에 있는 파일을 로드합니다.
  • #load "..\shared\mylogger.csx" 는 함수 폴더와 동일한 수준의 폴더 즉, wwwroot에 있는 파일을 로드합니다.

#load 지시문은 .cs 파일이 아닌 .csx 파일에서만 작동합니다.

메서드 반환 값에 바인딩

function.json에서 이름 $return을 사용하여 출력 바인딩에 메서드 반환 값을 사용할 수 있습니다.

{
    "name": "$return",
    "type": "blob",
    "direction": "out",
    "path": "output-container/{id}"
}

다음은 반환 값을 사용하는 C# 스크립트 코드와 비동기 예입니다.

public static string Run(WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return json;
}
public static Task<string> Run(WorkItem input, ILogger log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.LogInformation($"C# script processed queue message. Item={json}");
    return Task.FromResult(json);
}

성공적인 함수 실행이 항상 출력 바인딩으로 전달할 반환 값을 생성하는 경우에만 반환 값을 사용합니다. 그렇지 않으면 다음 섹션에 나와 있는 것처럼 ICollector 또는 IAsyncCollector를 사용합니다.

여러 출력 값 쓰기

출력 바인딩에 여러 값을 쓰거나 성공적인 함수 호출이 출력 바인딩에 전달할 값을 생성하지 않는 경우 ICollector 또는 IAsyncCollector 형식을 사용합니다. 이러한 형식은 메서드가 완료될 때 출력 바인딩에 기록되는 쓰기 전용 컬렉션입니다.

이 예제에서는 ICollector를 사용하여 동일한 큐에 여러 큐 메시지를 씁니다.

public static void Run(ICollector<string> myQueue, ILogger log)
{
    myQueue.Add("Hello");
    myQueue.Add("World!");
}

로깅

C#의 스트리밍 로그에 대한 출력을 기록하려면 ILogger 형식의 인수를 포함합니다. 이름을 log로 하는 것이 좋습니다. Azure Functions에서 Console.Write를 사용하지 마세요.

public static void Run(string myBlob, ILogger log)
{
    log.LogInformation($"C# Blob trigger function processed: {myBlob}");
}

참고 항목

TraceWriter 대신 사용할 수 있는 최신 로깅 프레임워크에 대한 자세한 내용은 .NET 클래스 라이브러리 개발자 가이드의 ILogger 설명서를 참조하세요.

사용자 지정 메트릭 로깅

ILoggerLogMetric 확장 메서드를 사용하여 Application Insights에서 사용자 지정 메트릭을 만들 수 있습니다. 다음은 샘플 메서드 호출입니다.

logger.LogMetric("TestMetric", 1234);

이 코드는 .NET용 Application Insights API를 사용하여 TrackMetric을 호출하는 대안입니다.

Async

비동기화 함수를 만들려면 async 키워드를 사용하고 Task 개체를 반환합니다.

public async static Task ProcessQueueMessageAsync(
        string blobName,
        Stream blobInput,
        Stream blobOutput)
{
    await blobInput.CopyToAsync(blobOutput, 4096);
}

out 매개 변수는 비동기 함수에 사용할 수 없습니다. 출력 바인딩에는 함수 반환 값 또는 수집기 개체를 대신 사용합니다.

취소 토큰

함수는 함수가 종료될 때 운영 체제가 코드에 알릴 수 있게 해주는 CancellationToken 매개 변수를 사용할 수 있습니다. 이 알림을 통해 함수가 예기치 않게 종료되어 데이터가 일관되지 않은 상태가 되는 것을 방지할 수 있습니다.

다음 예제에서는 임박한 함수 종료를 확인하는 방법을 보여 줍니다.

using System;
using System.IO;
using System.Threading;

public static void Run(
    string inputText,
    TextWriter logger,
    CancellationToken token)
{
    for (int i = 0; i < 100; i++)
    {
        if (token.IsCancellationRequested)
        {
            logger.WriteLine("Function was cancelled at iteration {0}", i);
            break;
        }
        Thread.Sleep(5000);
        logger.WriteLine("Normal processing for queue message={0}", inputText);
    }
}

네임스페이스 가져오기

네임스페이스를 가져와야 하는 경우 using 절과 함께 정상적으로 수행할 수 있습니다.

using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public static Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)

다음 네임스페이스를 자동으로 가져오므로 다음은 선택적입니다.

  • System
  • System.Collections.Generic
  • System.IO
  • System.Linq
  • System.Net.Http
  • System.Threading.Tasks
  • Microsoft.Azure.WebJobs
  • Microsoft.Azure.WebJobs.Host

외부 어셈블리 참조

프레임워크 어셈블리의 경우 #r "AssemblyName" 지시문을 사용하여 참조를 추가합니다.

#r "System.Web.Http"

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public static Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)

다음 어셈블리는 Azure Functions 호스팅 환경에 의해 자동으로 추가됩니다.

  • mscorlib
  • System
  • System.Core
  • System.Xml
  • System.Net.Http
  • Microsoft.Azure.WebJobs
  • Microsoft.Azure.WebJobs.Host
  • Microsoft.Azure.WebJobs.Extensions
  • System.Web.Http
  • System.Net.Http.Formatting

다음 어셈블리는 단순 이름 및 런타임 버전으로 참조될 수 있습니다.

  • Newtonsoft.Json
  • Microsoft.WindowsAzure.Storage*

*런타임 버전 4.x에서 삭제되었습니다.

코드에서 어셈블리는 다음 예와 같이 참조됩니다.

#r "AssemblyName"

사용자 지정 어셈블리 참조

사용자 지정 어셈블리를 참조하려면 공유 어셈블리 또는 프라이빗 어셈블리를 사용합니다.

  • 공유 어셈블리는 함수 앱 내의 모든 함수에서 공유됩니다. 사용자 지정 어셈블리를 참조하려면 함수 앱의 루트 폴더(wwwroot)에 있는 bin 폴더에 어셈블리를 업로드합니다.

  • 프라이빗 어셈블리는 지정된 함수 컨텍스트의 일부이며 여러 버전의 테스트용 로드를 지원합니다. 프라이빗 어셈블리는 함수 디렉터리의 bin 폴더에 업로드해야 합니다. #r "MyAssembly.dll"과 같은 파일 이름을 사용하여 어셈블리를 참조합니다.

함수 폴더에 파일을 업로드하는 방법에 대한 내용은 패키지 관리에 대한 섹션을 참조하세요.

감시 디렉터리

함수 스크립트 파일을 포함하는 디렉터리는 어셈블리 변경 내용이 자동으로 감시됩니다. 다른 디렉터리의 어셈블리 변경 내용을 감시하려면 host.jsonwatchDirectories 목록에 해당 디렉터리를 추가합니다.

NuGet 패키지 사용

바인딩 확장 패키지와 다른 NuGet 패키지가 모두 함수 앱에 추가되는 방식은 Functions 런타임의 대상 버전에 따라 다릅니다.

기본적으로 지원되는 Functions 확장 NuGet 패키지 집합은 확장 번들을 사용하여 C# 스크립트 함수 앱에서 사용할 수 있습니다. 자세한 내용은 확장 번들을 참조하세요.

어떤 이유로 프로젝트에서 확장 번들을 사용할 수 없는 경우 Azure Functions Core Tools를 사용하여 앱의 function.json 파일에 정의된 바인딩을 기반으로 확장을 설치할 수도 있습니다. Core Tools를 사용하여 확장을 등록할 때 --csx 옵션을 사용해야 합니다. 자세한 내용은 func extensions install을 참조하세요.

기본적으로 Core Tools는 function.json 파일을 읽고 필요한 패키지를 함수 앱의 파일 시스템(wwwroot) 루트에 있는 extensions.csproj C# 클래스 라이브러리 프로젝트 파일에 추가합니다. Core Tools는 dotnet.exe를 사용하므로 이 확장 파일에 대한 모든 NuGet 패키지 참조를 추가하는 데 사용할 수 있습니다. 설치하는 동안 Core Tools는 필요한 라이브러리를 설치하기 위해 extension.csproj를 빌드합니다. 다음은 Microsoft.ProjectOxford.Face 버전 1.1.0에 참조를 추가하는 예 extensions.csproj 파일입니다.

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netstandard2.0</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="Microsoft.ProjectOxford.Face" Version="1.1.0" />
    </ItemGroup>
</Project>

참고 항목

C# 스크립트(.csx)의 경우 TargetFrameworknetstandard2.0 값으로 설정해야 합니다. net6.0과 같은 다른 대상 프레임워크는 지원되지 않습니다.

사용자 지정 NuGet 피드를 사용하려면 함수 앱 루트 폴더의 Nuget.Config 파일에서 피드를 지정합니다. 자세한 내용은 참조 NuGet 동작 구성을 참조하세요.

포털에서만 프로젝트 작업을 하는 경우 사이트에서 직접 extensions.csproj 파일 또는 Nuget.Config 파일을 수동으로 만들어야 합니다. 자세한 내용은 수동으로 확장 설치를 참조하세요.

환경 변수

환경 변수 또는 앱 설정 값을 가져오려면 다음 코드 예제와 같이 System.Environment.GetEnvironmentVariable을 사용합니다.

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
    log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}

public static string GetEnvironmentVariable(string name)
{
    return name + ": " +
        System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}

재시도 정책

Functions는 두 가지 기본 다시 시도 정책을 지원합니다. 자세한 내용은 다시 시도 정책을 참조하세요.

function.json 파일의 재시도 정책은 다음과 같습니다.

{
    "disabled": false,
    "bindings": [
        {
            ....
        }
    ],
    "retry": {
        "strategy": "fixedDelay",
        "maxRetryCount": 4,
        "delayInterval": "00:00:10"
    }
}
function.json 속성 설명
전략 fixedDelay을 사용합니다.
maxRetryCount 필수입니다. 함수 실행당 허용되는 최대 재시도 횟수입니다. -1은 무기한으로 재시도하는 것을 의미합니다.
delayInterval 다시 시도 간에 사용되는 지연입니다. HH:mm:ss 형식을 사용하여 문자열로 지정합니다.

런타임에 바인딩

C# 및 기타 .NET 언어에서는 function.jsondeclarative 바인딩과 달리 명령적 바인딩 패턴을 사용할 수 있습니다. 명령적 바인딩은 바인딩 매개 변수를 디자인 타임이 아닌 런타임에 계산해야 할 경우 유용합니다. 이 패턴을 사용하면 함수 코드에서 지원되는 입력 및 출력 바인딩을 즉시 바인딩할 수 있습니다.

다음과 같이 명령적 바인딩을 정의합니다.

  • 원하는 명령적 바인딩에 대한 function.json에 항목을 포함하지 마세요.
  • 입력 매개 변수 Binder binder 또는 IBinder binder에 전달합니다.
  • 다음 C# 패턴을 사용하여 데이터 바인딩을 수행합니다.
using (var output = await binder.BindAsync<T>(new BindingTypeAttribute(...)))
{
    ...
}

BindingTypeAttribute는 바인딩을 정의하는 .NET 특성이며, T는 해당 바인딩 형식에서 지원되는 입력 또는 출력 형식입니다. Tout 매개 변수 형식(예: out JObject)일 수 없습니다. 예를 들어, Mobile Apps 테이블 출력 바인딩은 6가지 출력 형식을 지원하지만 T에는 ICollector<T> 또는 IAsyncCollector<T>만 사용할 수 있습니다.

단일 특성 예제

다음 예제 코드에서는 런타임에서 정의된 Blob경로를 사용하는 Storage Blob 출력 바인딩을 만든 다음, Blob에 문자열을 씁니다.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host.Bindings.Runtime;

public static async Task Run(string input, Binder binder)
{
    using (var writer = await binder.BindAsync<TextWriter>(new BlobAttribute("samples-output/path")))
    {
        writer.Write("Hello World!!");
    }
}

BlobAttributeStorage Blob 입력 또는 출력 바인딩을 정의하며, TextWriter는 지원되는 출력 바인딩 형식입니다.

다중 특성 예제

앞의 예제에서는 함수 앱의 주 Storage 계정 연결 문자열(AzureWebJobsStorage)에 대한 앱 설정을 가져옵니다. StorageAccountAttribute를 추가하고 BindAsync<T>()에 특성 배열을 전달하여 스토리지 계정에 사용할 사용자 지정 앱 설정을 지정할 수 있습니다. IBinder가 아닌 Binder 매개 변수를 사용합니다. 예시:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host.Bindings.Runtime;

public static async Task Run(string input, Binder binder)
{
    var attributes = new Attribute[]
    {
        new BlobAttribute("samples-output/path"),
        new StorageAccountAttribute("MyStorageAccount")
    };

    using (var writer = await binder.BindAsync<TextWriter>(attributes))
    {
        writer.Write("Hello World!");
    }
}

다음 표에는 각 바인딩 유형의 .NET 특성과 해당 특성이 정의된 패키지가 나열되어 있습니다.

바인딩 Attribute 참조 추가
Azure Cosmos DB Microsoft.Azure.WebJobs.DocumentDBAttribute #r "Microsoft.Azure.WebJobs.Extensions.CosmosDB"
Event Hubs Microsoft.Azure.WebJobs.ServiceBus.EventHubAttribute, Microsoft.Azure.WebJobs.ServiceBusAccountAttribute #r "Microsoft.Azure.Jobs.ServiceBus"
Mobile Apps Microsoft.Azure.WebJobs.MobileTableAttribute #r "Microsoft.Azure.WebJobs.Extensions.MobileApps"
Notification Hubs Microsoft.Azure.WebJobs.NotificationHubAttribute #r "Microsoft.Azure.WebJobs.Extensions.NotificationHubs"
Service Bus Microsoft.Azure.WebJobs.ServiceBusAttribute, Microsoft.Azure.WebJobs.ServiceBusAccountAttribute #r "Microsoft.Azure.WebJobs.ServiceBus"
스토리지 큐 Microsoft.Azure.WebJobs.QueueAttribute, Microsoft.Azure.WebJobs.StorageAccountAttribute
Storage Blob Microsoft.Azure.WebJobs.BlobAttribute, Microsoft.Azure.WebJobs.StorageAccountAttribute
Storage 테이블 Microsoft.Azure.WebJobs.TableAttribute, Microsoft.Azure.WebJobs.StorageAccountAttribute
Twilio Microsoft.Azure.WebJobs.TwilioSmsAttribute #r "Microsoft.Azure.WebJobs.Extensions.Twilio"

C# 스크립트 앱을 C# 프로젝트로 변환

C# 스크립트 함수 앱을 컴파일된 C# 클래스 라이브러리 프로젝트로 변환하는 가장 쉬운 방법은 새 프로젝트로 시작하는 것입니다. 그런 다음 각 함수에 대해 함수 폴더의 각 run.csx 파일과 function.json 파일의 코드와 구성을 하나의 새로운 .cs 클래스 라이브러리 코드 파일로 마이그레이션할 수 있습니다. 예를 들어, HelloWorld라는 C# 스크립트 함수가 있는 경우 HelloWorld/run.csxHelloWorld/function.json이라는 두 개의 파일이 있습니다. 이 함수의 경우 새 클래스 라이브러리 프로젝트에 HelloWorld.cs라는 코드 파일을 만듭니다.

포털 편집을 위해 C# 스크립트를 사용하는 경우 앱 콘텐츠를 로컬 컴퓨터에 다운로드할 수 있습니다. 콘텐츠 및 Visual Studio 프로젝트 대신 사이트 콘텐츠 옵션을 선택합니다. 프로젝트를 생성할 필요가 없으며 다운로드에 애플리케이션 설정을 포함하지 마세요. 새로운 개발 환경을 정의하고 있으며 이 환경은 호스트된 앱 환경과 동일한 권한을 가져서는 안 됩니다.

이 지침에서는 C# 스크립트 함수(Functions 호스트와 함께 프로세스 내에서 실행됨)를 격리된 작업자 프로세스에서 실행되는 C# 클래스 라이브러리 함수로 변환하는 방법을 보여 줍니다.

  1. 원하는 빠른 시작에서 함수 앱 프로젝트 만들기 섹션을 완료합니다.


  1. 원본 C# 스크립트 코드에 extensions.csproj 파일 또는 function.proj 파일이 포함된 경우 이러한 파일에서 패키지 참조를 복사하여 Functions 핵심 종속성이 있는 동일한 ItemGroup에 있는 새 프로젝트의 .csproj 파일에 추가합니다.

    변환은 종속성의 최신 버전으로 업데이트할 수 있는 좋은 기회를 제공합니다. 이렇게 하려면 이후 단계에서 추가 코드 변경이 필요할 수 있습니다.

  2. extensionBundles 섹션을 제외하고 원본 host.json 파일의 콘텐츠를 새 프로젝트의 host.json 파일에 복사합니다(컴파일된 C# 프로젝트는 확장 번들을 사용하지 않으며 함수에서 사용하는 모든 확장에 대한 참조를 명시적으로 추가해야 함). Host.json 파일을 병합할 때 host.json 스키마의 버전이 지정되어 있으며 대부분의 앱은 버전 2.0을 사용해야 합니다. extensions 섹션의 콘텐츠는 함수에서 사용하는 바인딩 확장의 특정 버전에 따라 다를 수 있습니다. 특정 버전에 맞게 host.json을 올바르게 구성하는 방법을 알아보려면 개별 확장 참조 문서를 참조하세요.

  3. #load 지시문에서 참조하는 공유 파일의 경우 각 공유 참조에 대해 새 .cs 파일을 만듭니다. 각 공유 클래스 정의에 대해 새 .cs 파일을 만드는 것이 가장 간단합니다. 클래스가 없는 정적 메서드가 있는 경우 이러한 메서드에 대해 새 클래스를 정의해야 합니다.

  4. 원본 프로젝트의 각 <FUNCTION_NAME> 폴더에 대해 다음 작업을 수행합니다.

    1. <FUNCTION_NAME>.cs라는 새 파일을 만들고 <FUNCTION_NAME>을 C# 스크립트 함수를 정의한 폴더 이름으로 바꿉니다. 다음과 같은 방법으로 트리거별 템플릿 중 하나에서 새 함수 코드 파일을 만들 수 있습니다.

      func new --name <FUNCTION_NAME> 명령을 사용하고 프롬프트에서 올바른 트리거 템플릿을 선택합니다.

    2. run.csx 파일에서 using 문을 복사하여 새 파일에 추가합니다. #r 지시문은 필요하지 않습니다.

    3. run.csx 파일의 모든 #load 문에 대해 공유 코드에 사용한 네임스페이스에 대한 새 using 문을 추가합니다.

    4. 새 파일에서 프로젝트에 사용 중인 네임스페이스 아래에 함수에 대한 클래스를 정의합니다.

    5. RunHandler 또는 이와 유사한 이름의 새 메서드를 작성합니다. 이 새로운 메서드는 함수의 새로운 진입점 역할을 합니다.

    6. 함수를 나타내는 정적 메서드를 호출하는 모든 함수와 함께 run.csx에서 새 클래스에 두 번째 메서드로 복사합니다. 이전 단계에서 만든 새 메서드에서 이 정적 메서드를 호출합니다. 이 간접 단계는 업그레이드를 계속하면서 차이점을 탐색하는 데 도움이 됩니다. 원래 메서드를 정확히 동일하게 유지하고 새 컨텍스트에서 해당 입력을 간단히 제어할 수 있습니다. 새 메서드에 대한 매개 변수를 만든 다음 이를 정적 메서드 호출에 전달해야 할 수도 있습니다. 마이그레이션이 의도한 대로 작동했음을 확인한 후 이 추가 간접 수준을 제거할 수 있습니다.

    7. function.json 파일의 각 바인딩에 대해 해당 특성을 새 메서드에 추가합니다. 바인딩 예를 빠르게 찾으려면 예를 기반으로 수동으로 바인딩 추가를 참조하세요.

    8. 아직 추가하지 않은 경우 바인딩에 필요한 확장 패키지를 프로젝트에 추가합니다.

  5. local.settings.json 파일Values 컬렉션에서 앱에 필요한 애플리케이션 설정을 다시 만듭니다.

  6. 프로젝트가 로컬에서 실행되는지 확인합니다.

    명령줄에서 앱을 실행하려면 func start를 사용합니다. 자세한 내용은 로컬에서 함수 실행을 참조하세요.

  7. Azure의 새 함수 앱에 프로젝트를 게시합니다.

    Azure 리소스를 만들고func azure functionapp publish <APP_NAME> 명령을 사용하여 Azure에 코드 프로젝트를 배포합니다. 자세한 내용은 프로젝트 파일 배포를 참조하세요.

함수 변환 예

이 섹션에서는 단일 함수에 대한 마이그레이션의 예를 보여 줍니다.

C# 스크립팅의 원래 함수에는 두 개의 파일이 있습니다.

  • HelloWorld/function.json
  • HelloWorld/run.csx

다음은 HelloWorld/function.json의 내용입니다.

{
  "bindings": [
    {
      "authLevel": "FUNCTION",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ]
}

다음은 HelloWorld/run.csx의 내용입니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    string responseMessage = string.IsNullOrEmpty(name)
        ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
}

ASP.NET Core 통합을 사용하여 격리된 작업자 모델로 마이그레이션한 후에는 단일 HelloWorld.cs로 바뀝니다.

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

namespace MyFunctionApp
{
    public class HelloWorld
    {
        private readonly ILogger _logger;

        public HelloWorld(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<HelloWorld>();
        }

        [Function("HelloWorld")]
        public async Task<IActionResult> RunHandler([HttpTrigger(AuthorizationLevel.Function, "get")] HttpRequest req)
        {
            return await Run(req, _logger);
        }

        // From run.csx
        public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                        : $"Hello, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }
}

바인딩 구성 및 예

이 섹션에는 C# 스크립트에서 트리거 및 바인딩을 정의하기 위한 참조와 예가 포함되어 있습니다.

Blob 트리거

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type blobTrigger로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 Blob을 나타내는 변수의 이름입니다.
path 모니터링할 컨테이너입니다. Blob 이름 패턴일 수 있습니다.
connection Azure Blob에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예에서는 function.json 파일의 blob 트리거 정의와 바인딩을 사용하는 코드를 보여 줍니다. 함수는 samples-workitems컨테이너에서 Blob을 추가하거나 업데이트할 때 로그를 씁니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "disabled": false,
    "bindings": [
        {
            "name": "myBlob",
            "type": "blobTrigger",
            "direction": "in",
            "path": "samples-workitems/{name}",
            "connection":"MyStorageAccountAppSetting"
        }
    ]
}

blob 트리거 경로 samples-workitems/{name}의 문자열 {name}은 함수 코드에서 사용할 수 있는 바인딩 식을 만들어 트리거 blob의 파일 이름에 액세스합니다. 자세한 내용은 Blob 이름 패턴을 참조하세요.

Stream에 바인딩되는 C# 스크립트 코드는 다음과 같습니다.

public static void Run(Stream myBlob, string name, ILogger log)
{
   log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes");
}

CloudBlockBlob에 바인딩되는 C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.WindowsAzure.Storage"

using Microsoft.WindowsAzure.Storage.Blob;

public static void Run(CloudBlockBlob myBlob, string name, ILogger log)
{
    log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name}\nURI:{myBlob.StorageUri}");
}

Blob 입력

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type blob로 설정해야 합니다.
direction in로 설정해야 합니다.
이름 함수 코드에서 Blob을 나타내는 변수의 이름입니다.
path Blob에 대한 경로입니다.
connection Azure Blob에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 Blob 입력 및 출력 바인딩을 보여 줍니다. 함수는 텍스트 Blob의 복사본을 만듭니다. 함수는 복사할 Blob의 이름을 포함하는 큐 메시지에 의해 트리거됩니다. 새 Blob의 이름은 {originalblobname}-Copy입니다.

function.json 파일에서 queueTrigger 메타데이터 속성은 path 속성에서 Blob 이름을 지정하는 데 사용됩니다.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

public static void Run(string myQueueItem, string myInputBlob, out string myOutputBlob, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    myOutputBlob = myInputBlob;
}

Blob 출력

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type blob로 설정해야 합니다.
direction out로 설정해야 합니다.
이름 함수 코드에서 Blob을 나타내는 변수의 이름입니다.
path Blob에 대한 경로입니다.
connection Azure Blob에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 Blob 입력 및 출력 바인딩을 보여 줍니다. 함수는 텍스트 Blob의 복사본을 만듭니다. 함수는 복사할 Blob의 이름을 포함하는 큐 메시지에 의해 트리거됩니다. 새 Blob의 이름은 {originalblobname}-Copy입니다.

function.json 파일에서 queueTrigger 메타데이터 속성은 path 속성에서 Blob 이름을 지정하는 데 사용됩니다.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "myInputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    },
    {
      "name": "myOutputBlob",
      "type": "blob",
      "path": "samples-workitems/{queueTrigger}-Copy",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

public static void Run(string myQueueItem, string myInputBlob, out string myOutputBlob, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    myOutputBlob = myInputBlob;
}

RabbitMQ 트리거

다음 예제는 function.json 파일의 RabbitMQ 트리거 바인딩과 이 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 RabbitMQ 메시지를 읽고 로그합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{​​
    "bindings": [
        {​​
            "name": "myQueueItem",
            "type": "rabbitMQTrigger",
            "direction": "in",
            "queueName": "queue",
            "connectionStringSetting": "rabbitMQConnectionAppSetting"
        }​​
    ]
}​​

C# 스크립트 코드는 다음과 같습니다.

using System;

public static void Run(string myQueueItem, ILogger log)
{​​
    log.LogInformation($"C# Script RabbitMQ trigger function processed: {​​myQueueItem}​​");
}​​

큐 트리거

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type queueTrigger로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction function.json 파일에서만 적용됩니다. in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 큐 항목 페이로드를 포함하는 변수 이름입니다.
queueName 폴링할 큐의 이름입니다.
connection Azure 큐에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예제에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 큐 트리거 바인딩을 보여 줍니다. 함수는 myqueue-items 큐를 폴링하고 큐 항목이 처리될 때마다 로그를 기록합니다.

function.json 파일은 다음과 같습니다.

{
    "disabled": false,
    "bindings": [
        {
            "type": "queueTrigger",
            "direction": "in",
            "name": "myQueueItem",
            "queueName": "myqueue-items",
            "connection":"MyStorageConnectionAppSetting"
        }
    ]
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.WindowsAzure.Storage"

using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Queue;
using System;

public static void Run(CloudQueueMessage myQueueItem, 
    DateTimeOffset expirationTime, 
    DateTimeOffset insertionTime, 
    DateTimeOffset nextVisibleTime,
    string queueTrigger,
    string id,
    string popReceipt,
    int dequeueCount,
    ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem.AsString}\n" +
        $"queueTrigger={queueTrigger}\n" +
        $"expirationTime={expirationTime}\n" +
        $"insertionTime={insertionTime}\n" +
        $"nextVisibleTime={nextVisibleTime}\n" +
        $"id={id}\n" +
        $"popReceipt={popReceipt}\n" + 
        $"dequeueCount={dequeueCount}");
}

큐 출력

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type queue로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction out로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 큐를 나타내는 변수의 이름입니다. $return으로 설정하여 함수 반환 값을 참조합니다.
queueName 큐 이름입니다.
connection Azure 큐에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예제에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 HTTP 트리거 바인딩을 보여 줍니다. 이 함수는 수신한 각 HTTP 요청에 대한 CustomQueueMessage 개체 페이로드를 사용하여 큐 항목을 만듭니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "type": "httpTrigger",
      "direction": "in",
      "authLevel": "function",
      "name": "input"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "$return",
      "queueName": "outqueue",
      "connection": "MyStorageConnectionAppSetting"
    }
  ]
}

단일 큐 메시지를 만드는 C# 스크립트 코드는 다음과 같습니다.

public class CustomQueueMessage
{
    public string PersonName { get; set; }
    public string Title { get; set; }
}

public static CustomQueueMessage Run(CustomQueueMessage input, ILogger log)
{
    return input;
}

ICollector 또는 IAsyncCollector 매개 변수를 사용하여 한 번에 여러 메시지를 보낼 수 있습니다. 여러 개의 메시지를 보내는 C# 스크립트 코드, HTTP 요청 데이터를 포함하는 코드 및 하드코딩된 값을 포함하는 코드는 다음과 같습니다.

public static void Run(
    CustomQueueMessage input, 
    ICollector<CustomQueueMessage> myQueueItems, 
    ILogger log)
{
    myQueueItems.Add(input);
    myQueueItems.Add(new CustomQueueMessage { PersonName = "You", Title = "None" });
}

테이블 입력

이 섹션에서는 Tables API 확장 버전에 대한 지원만 간략하게 설명합니다.

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type table로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
direction in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 테이블 또는 엔터티를 나타내는 변수의 이름입니다.
tableName 테이블의 이름입니다.
partitionKey 선택 사항. 읽을 테이블 엔터티의 파티션 키입니다.
rowKey 선택 사항. 읽을 테이블 엔터티의 행 키입니다. take 또는 filter와 함께 사용할 수 없습니다.
take 선택 사항. 반환할 최대 엔터티 수입니다. rowKey와 함께 사용할 수 없습니다.
filter 선택 사항. 테이블에서 반환할 엔터티에 대한 OData 필터 식입니다. rowKey와 함께 사용할 수 없습니다.
connection 테이블 서비스에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 테이블 입력 바인딩을 보여 줍니다. 함수는 큐 트리거를 사용하여 단일 테이블 행을 읽습니다.

function.json 파일은 partitionKeyrowKey를 지정합니다. rowKey{queueTrigger}는 행 키가 큐 메시지 문자열에서 온다는 것을 나타냅니다.

{
  "bindings": [
    {
      "queueName": "myqueue-items",
      "connection": "MyStorageConnectionAppSetting",
      "name": "myQueueItem",
      "type": "queueTrigger",
      "direction": "in"
    },
    {
      "name": "personEntity",
      "type": "table",
      "tableName": "Person",
      "partitionKey": "Test",
      "rowKey": "{queueTrigger}",
      "connection": "MyStorageConnectionAppSetting",
      "direction": "in"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

#r "Azure.Data.Tables"
using Microsoft.Extensions.Logging;
using Azure.Data.Tables;

public static void Run(string myQueueItem, Person personEntity, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");
    log.LogInformation($"Name in Person entity: {personEntity.Name}");
}

public class Person : ITableEntity
{
    public string Name { get; set; }

    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public DateTimeOffset? Timestamp { get; set; }
    public ETag ETag { get; set; }
}

테이블 출력

이 섹션에서는 Tables API 확장 버전에 대한 지원만 간략하게 설명합니다.

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type table로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
direction out로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
이름 테이블 또는 엔터티를 나타내는 함수 코드에서 사용되는 변수 이름입니다. $return으로 설정하여 함수 반환 값을 참조합니다.
tableName 쓸 테이블의 이름입니다.
partitionKey 쓸 테이블 엔터티의 파티션 키입니다.
rowKey 쓸 테이블 엔터티의 행 키입니다.
connection 테이블 서비스에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예에서는 바인딩을 사용하는 function.json 파일 및 C# 스크립트 코드에서 테이블 출력 바인딩을 보여 줍니다. 함수는 여러 테이블 엔터티를 씁니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "name": "input",
      "type": "manualTrigger",
      "direction": "in"
    },
    {
      "tableName": "Person",
      "connection": "MyStorageConnectionAppSetting",
      "name": "tableBinding",
      "type": "table",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

public static void Run(string input, ICollector<Person> tableBinding, ILogger log)
{
    for (int i = 1; i < 10; i++)
        {
            log.LogInformation($"Adding Person entity {i}");
            tableBinding.Add(
                new Person() { 
                    PartitionKey = "Test", 
                    RowKey = i.ToString(), 
                    Name = "Name" + i.ToString() }
                );
        }

}

public class Person
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }
}

타이머 트리거

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type timerTrigger로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 타이머 개체를 나타내는 변수의 이름입니다.
schedule CRON 식 또는 TimeSpan 값입니다. App Service 계획에서 함수 앱을 실행 중인 경우에만 TimeSpan을 사용할 수 있습니다. "%ScheduleAppSetting%" 예제와 같이 앱 설정에서 일정 식을 배치하고 이 속성을 % 기호에서 래핑된 앱 설정 이름으로 설정할 수 있습니다.
runOnStartup true인 경우 함수는 런타임이 시작될 때 호출됩니다. 예를 들어 비활성으로 인해 유휴 상태로 전환된 후에 함수 앱이 작동될 때 런타임이 시작됩니다. 함수 변경으로 인해 함수 앱이 다시 시작될 때 및 함수 앱이 확장될 때에도 런타임이 시작됩니다. 주의해서 사용합니다.runOnStartup은 특히 프로덕션 환경에서 true로 설정되는 경우가 거의 없습니다.
useMonitor true 또는 false로 설정하여 일정을 모니터링해야 하는지를 나타냅니다. 일정 모니터링은 일정 발생을 유지하여 함수 앱 인스턴스가 다시 시작하는 경우에도 일정을 올바르게 유지하도록 지원합니다. 명시적으로 설정하지 않는 경우 되풀이 간격이 1분을 넘는 큰 일정에서 기본값은 true입니다. 분당 한 번 넘게 트리거되는 일정에서 기본값은 false입니다.

다음 예에서는 function.json 파일의 타이머 트리거 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 함수는 누락된 일정으로 인해 이 함수 호출이 발생했는지를 나타내는 로그를 씁니다. TimerInfo 개체가 함수에 전달됩니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "schedule": "0 */5 * * * *",
    "name": "myTimer",
    "type": "timerTrigger",
    "direction": "in"
}

C# 스크립트 코드는 다음과 같습니다.

public static void Run(TimerInfo myTimer, ILogger log)
{
    if (myTimer.IsPastDue)
    {
        log.LogInformation("Timer is running late!");
    }
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}" );  
}

HTTP 트리거

다음 표에서는 function.json 파일에서 설정한 트리거 구성 속성을 설명합니다.

function.json 속성 설명
type 필수 - httpTrigger으로 설정해야 합니다.
direction 필수 - in으로 설정해야 합니다.
이름 필수 - 요청 또는 요청 본문의 함수 코드에 사용되는 변수 이름입니다.
authLevel 키가 있는 경우 함수를 호출하기 위해 요청에 포함되어야 하는 키를 결정합니다. 지원되는 값은 권한 부여 수준을 참조하세요.
메서드 함수에서 응답할 HTTP 메서드의 배열입니다. 이 속성을 지정하지 않으면 함수에서 모든 HTTP 메서드에 응답합니다. HTTP 엔드포인트 사용자 지정을 참조하세요.
route 경로 템플릿을 정의하여 함수에서 응답할 요청 URL을 제어합니다. 값을 제공하지 않을 경우 기본값은 <functionname>입니다. 자세한 내용은 HTTP 엔드포인트 사용자 지정을 참조하세요.
webHookType 버전 1.x 런타임에서만 지원됩니다.

HTTP 트리거가 지정된 공급자의 웹후크 수신기(receiver)로 작동하도록 구성합니다. 지원되는 값은 WebHook 형식을 참조하세요.

다음 예제는 function.json 파일의 트리거 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 함수는 쿼리 문자열이나 HTTP 요청의 본문에서 name 매개 변수를 찾습니다.

function.json 파일은 다음과 같습니다.

{
    "disabled": false,
    "bindings": [
        {
            "authLevel": "function",
            "name": "req",
            "type": "httpTrigger",
            "direction": "in",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "name": "$return",
            "type": "http",
            "direction": "out"
        }
    ]
}

다음은 HttpRequest에 바인딩하는 C# 스크립트 코드입니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];
    
    string requestBody = String.Empty;
    using (StreamReader streamReader =  new  StreamReader(req.Body))
    {
        requestBody = await streamReader.ReadToEndAsync();
    }
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;
    
    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

HttpRequest 대신 사용자 지정 개체에 바인딩할 수 있습니다. 이 개체는 요청 본문에서 만들어지고 JSON으로 구문 분석됩니다. 마찬가지로, 형식을 HTTP 응답 출력 바인딩으로 전달할 수도 있습니다. 그러면 200 상태 코드를 갖는 응답 본문으로 반환됩니다.

using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public static string Run(Person person, ILogger log)
{   
    return person.Name != null
        ? (ActionResult)new OkObjectResult($"Hello, {person.Name}")
        : new BadRequestObjectResult("Please pass an instance of Person.");
}

public class Person {
     public string Name {get; set;}
}

HTTP 출력

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

속성 설명
type http로 설정해야 합니다.
direction out로 설정해야 합니다.
이름 응답에 대한 함수 코드에 사용되는 변수 이름이거나 반환 값을 사용하는 $return입니다.

Event Hubs 트리거

다음 표에서는 function.json 파일에서 설정한 트리거 구성 속성을 설명합니다.

function.json 속성 설명
type eventHubTrigger로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 이벤트 항목을 나타내는 변수의 이름입니다.
eventHubName Functions 2.x 이상. 이벤트 허브의 이름입니다. 이벤트 허브 이름이 연결 문자열에 있는 경우 해당 값은 런타임 시 이 속성을 재정의합니다. 앱 설정%eventHubName%을 통해 참조할 수 있습니다. 버전 1.x에서 이 속성의 이름은 path입니다.
consumerGroup 허브에서 이벤트를 구독하는 데 사용되는 소비자 그룹을 설정하는 선택적 속성입니다. 생략한 경우 $Default 소비자 그룹이 사용됩니다.
connection Event Hubs에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.

다음 예제에서는 function.json 파일의 Event Hubs 트리거 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 Event Hubs 트리거의 메시지 본문을 기록합니다.

다음 예제에서는 Functions 런타임 버전 2.x 이상 버전에 대한 function.json 파일의 Event Hubs 바인딩 데이터를 보여 줍니다.

{
  "type": "eventHubTrigger",
  "name": "myEventHubMessage",
  "direction": "in",
  "eventHubName": "MyEventHub",
  "connection": "myEventHubReadConnectionAppSetting"
}

C# 스크립트 코드는 다음과 같습니다.

using System;

public static void Run(string myEventHubMessage, TraceWriter log)
{
    log.Info($"C# function triggered to process a message: {myEventHubMessage}");
}

함수 코드에서 이벤트 메타데이터에 액세스하려면 EventData 개체에 바인딩합니다. 메서드 시그니처의 바인딩 식을 사용하여 동일한 속성에 액세스할 수도 있습니다. 다음 예제에서는 동일한 데이터를 가져오는 두 가지 방법을 모두 보여줍니다.

#r "Microsoft.Azure.EventHubs"

using System.Text;
using System;
using Microsoft.ServiceBus.Messaging;
using Microsoft.Azure.EventHubs;

public void Run(EventData myEventHubMessage,
    DateTime enqueuedTimeUtc,
    Int64 sequenceNumber,
    string offset,
    TraceWriter log)
{
    log.Info($"Event: {Encoding.UTF8.GetString(myEventHubMessage.Body)}");
    log.Info($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
    log.Info($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
    log.Info($"Offset={myEventHubMessage.SystemProperties.Offset}");

    // Metadata accessed by using binding expressions
    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"SequenceNumber={sequenceNumber}");
    log.Info($"Offset={offset}");
}

일괄 처리에서 이벤트를 수신하려면 string 또는 EventData 배열을 만듭니다.

public static void Run(string[] eventHubMessages, TraceWriter log)
{
    foreach (var message in eventHubMessages)
    {
        log.Info($"C# function triggered to process a message: {message}");
    }
}

Event Hubs 출력

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type eventHub로 설정해야 합니다.
direction out로 설정해야 합니다. 이 매개 변수는 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
이름 이벤트를 나타내는 함수 코드에서 사용되는 변수 이름입니다.
eventHubName Functions 2.x 이상. 이벤트 허브의 이름입니다. 이벤트 허브 이름이 연결 문자열에 있는 경우 해당 값은 런타임 시 이 속성을 재정의합니다. Functions 1.x에서 이 속성의 이름은 path입니다.
connection Event Hubs에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 자세한 내용은 연결을 참조하세요.

다음 예에서는 function.json 파일의 이벤트 허브 트리거 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 함수는 이벤트 허브로 메시지를 씁니다.

다음 예제에서는 Functions 런타임 버전 2.x 이상 버전에 대한 function.json 파일의 Event Hubs 바인딩 데이터를 보여 줍니다.

{
    "type": "eventHub",
    "name": "outputEventHubMessage",
    "eventHubName": "myeventhub",
    "connection": "MyEventHubSendAppSetting",
    "direction": "out"
}

단일 메시지를 만드는 C# 스크립트 코드는 다음과 같습니다.

using System;
using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, out string outputEventHubMessage, ILogger log)
{
    String msg = $"TimerTriggerCSharp1 executed at: {DateTime.Now}";
    log.LogInformation(msg);   
    outputEventHubMessage = msg;
}

여러 메시지를 만드는 C# 스크립트 코드는 다음과 같습니다.

public static void Run(TimerInfo myTimer, ICollector<string> outputEventHubMessage, ILogger log)
{
    string message = $"Message created at: {DateTime.Now}";
    log.LogInformation(message);
    outputEventHubMessage.Add("1 " + message);
    outputEventHubMessage.Add("2 " + message);
}

Event Grid 트리거

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다. EventGridTrigger 특성에서 설정할 생성자 매개 변수 또는 속성은 없습니다.

function.json 속성 설명
type 필수 - eventGridTrigger으로 설정해야 합니다.
direction 필수 - in으로 설정해야 합니다.
이름 필수 - 이벤트 데이터를 수신하는 매개 변수에 대한 함수 코드에 사용되는 변수 이름입니다.

다음 예제는 function.json 파일에 정의된 Event Grid 트리거를 보여 줍니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

다음은 EventGridEvent 바인딩 매개 변수를 사용하는 C# 스크립트 함수의 예제입니다.

#r "Azure.Messaging.EventGrid"
using Azure.Messaging.EventGrid;
using Microsoft.Extensions.Logging;

public static void Run(EventGridEvent eventGridEvent, ILogger log)
{
    log.LogInformation(eventGridEvent.Data.ToString());
}

다음은 JObject 바인딩 매개 변수를 사용하는 C# 스크립트 함수의 예제입니다.

#r "Newtonsoft.Json"

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static void Run(JObject eventGridEvent, TraceWriter log)
{
    log.Info(eventGridEvent.ToString(Formatting.Indented));
}

Event Grid 출력

다음 표에서는 function.json 파일에서 설정한 C# 스크립트의 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type eventGrid로 설정해야 합니다.
direction out로 설정해야 합니다. 이 매개 변수는 사용자가 Azure Portal에서 바인딩을 만들 때 자동으로 설정됩니다.
이름 이벤트를 나타내는 함수 코드에서 사용되는 변수 이름입니다.
topicEndpointUri MyTopicEndpointUri와 같이 사용자 지정 항목에 대한 URI를 포함하는 앱 설정의 이름입니다.
topicKeySetting 사용자 지정 항목에 대한 액세스 키가 포함된 앱 설정의 이름입니다.

다음 예제에서는 function.json 파일에 있는 Event Grid 출력 바인딩 데이터를 보여줍니다.

{
    "type": "eventGrid",
    "name": "outputEvent",
    "topicEndpointUri": "MyEventGridTopicUriSetting",
    "topicKeySetting": "MyEventGridTopicKeySetting",
    "direction": "out"
}

단일 이벤트를 만드는 C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.EventGrid"
using System;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, out EventGridEvent outputEvent, ILogger log)
{
    outputEvent = new EventGridEvent("message-id", "subject-name", "event-data", "event-type", DateTime.UtcNow, "1.0");
}

여러 이벤트를 만드는 C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.EventGrid"
using System;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;

public static void Run(TimerInfo myTimer, ICollector<EventGridEvent> outputEvent, ILogger log)
{
    outputEvent.Add(new EventGridEvent("message-id-1", "subject-name", "event-data", "event-type", DateTime.UtcNow, "1.0"));
    outputEvent.Add(new EventGridEvent("message-id-2", "subject-name", "event-data", "event-type", DateTime.UtcNow, "1.0"));
}

Service Bus 트리거

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type serviceBusTrigger로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction in로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 큐 또는 토픽 메시지를 나타내는 변수의 이름입니다.
queueName 모니터링할 큐의 이름입니다. 토픽이 아닌 큐를 모니터링하는 경우에만 설정합니다.
topicName 모니터링할 토픽의 이름입니다. 큐가 아닌 토픽을 모니터링하는 경우에만 설정합니다.
subscriptionName 모니터링할 구독의 이름입니다. 큐가 아닌 토픽을 모니터링하는 경우에만 설정합니다.
connection Service Bus에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.
accessRights 연결 문자열에 대한 액세스 권한입니다. 사용 가능한 값은 managelisten입니다. 기본값은 manage이며, connection관리 권한이 있음을 의미합니다. 관리 권한이 없는 연결 문자열을 사용하는 경우 accessRights을 "listen"으로 설정합니다. 그렇지 않으면 함수 런타임은 관리 권한이 필요한 작업 시도를 실패할 수 있습니다. Azure Functions 버전 2.x 이상에서는 최신 버전의 Service Bus SDK가 관리 작업을 지원하지 않으므로 이 속성을 사용할 수 없습니다.
isSessionsEnabled true세션 인식 큐나 구독에 연결하는 경우 입니다. false 그렇지 않으면 기본값입니다.
autoComplete true 트리거가 처리 후 자동으로 complete를 호출해야 하는지 아니면 함수 코드가 수동으로 complete를 호출하는지 여부입니다.

false로 설정은 C#에서만 지원됩니다.

true로 설정한 경우 함수 실행이 성공적으로 완료되면 트리거가 자동으로 메시지를 완료하고 그렇지 않으면 메시지가 중단됩니다.
<br/false로 설정하면 ServiceBusReceiver 메서드를 호출하여 메시지, 세션 또는 일괄 처리를 완료, 중단 또는 배달 못하도록 합니다. 예외가 발생하고 ServiceBusReceiver 메서드가 호출되지 않으면 잠금이 유지됩니다. 잠금이 만료되면 DeliveryCount가 증가하여 메시지가 다시 큐에 추가되고 잠금이 자동으로 갱신됩니다.

Azure Functions 2.x 이상에서만 이 속성을 사용할 수 있습니다.

다음 예에서는 function.json 파일의 Service Bus 트리거 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 함수는 메시지 메타데이터를 읽고 Service Bus 큐 메시지를 기록합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
"bindings": [
    {
    "queueName": "testqueue",
    "connection": "MyServiceBusConnection",
    "name": "myQueueItem",
    "type": "serviceBusTrigger",
    "direction": "in"
    }
],
"disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System;

public static void Run(string myQueueItem,
    Int32 deliveryCount,
    DateTime enqueuedTimeUtc,
    string messageId,
    TraceWriter log)
{
    log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}");

    log.Info($"EnqueuedTimeUtc={enqueuedTimeUtc}");
    log.Info($"DeliveryCount={deliveryCount}");
    log.Info($"MessageId={messageId}");
}

Service Bus 출력

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type serviceBus로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
direction out로 설정해야 합니다. 이 속성은 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 함수 코드에서 큐 또는 토픽 메시지를 나타내는 변수의 이름입니다. "$return"으로 설정하여 함수 반환 값을 참조합니다.
queueName 큐 이름. 토픽이 아닌 큐 메시지를 보내는 경우에만 설정합니다.
topicName 항목의 이름입니다. 큐가 아닌 토픽 메시지를 보내는 경우에만 설정합니다.
connection Service Bus에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 연결을 참조하세요.
accessRights(v1만 해당) 연결 문자열에 대한 액세스 권한입니다. 사용 가능한 값은 managelisten입니다. 기본값은 manage이며, connection관리 권한이 있음을 의미합니다. 관리 권한이 없는 연결 문자열을 사용하는 경우 accessRights을 "listen"으로 설정합니다. 그렇지 않으면 함수 런타임은 관리 권한이 필요한 작업 시도를 실패할 수 있습니다. Azure Functions 버전 2.x 이상에서는 최신 버전의 Service Bus SDK가 관리 작업을 지원하지 않으므로 이 속성을 사용할 수 없습니다.

다음 예에서는 function.json 파일의 Service Bus 출력 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 함수는 타이머 트리거를 사용하여 15초마다 큐 메시지를 보냅니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "bindings": [
        {
            "schedule": "0/15 * * * * *",
            "name": "myTimer",
            "runsOnStartup": true,
            "type": "timerTrigger",
            "direction": "in"
        },
        {
            "name": "outputSbQueue",
            "type": "serviceBus",
            "queueName": "testqueue",
            "connection": "MyServiceBusConnection",
            "direction": "out"
        }
    ],
    "disabled": false
}

단일 메시지를 만드는 C# 스크립트 코드는 다음과 같습니다.

public static void Run(TimerInfo myTimer, ILogger log, out string outputSbQueue)
{
    string message = $"Service Bus queue message created at: {DateTime.Now}";
    log.LogInformation(message); 
    outputSbQueue = message;
}

여러 메시지를 만드는 C# 스크립트 코드는 다음과 같습니다.

public static async Task Run(TimerInfo myTimer, ILogger log, IAsyncCollector<string> outputSbQueue)
{
    string message = $"Service Bus queue messages created at: {DateTime.Now}";
    log.LogInformation(message); 
    await outputSbQueue.AddAsync("1 " + message);
    await outputSbQueue.AddAsync("2 " + message);
}

Azure Cosmos DB v2 트리거

이 섹션에서는 확장 버전 4.x+에 대한 지원에 대해서만 설명합니다.

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type cosmosDBTrigger로 설정해야 합니다.
direction in로 설정해야 합니다. 이 매개 변수는 사용자가 Azure Portal에서 트리거를 만들 때 자동으로 설정됩니다.
이름 변경 사항이 포함된 문서 목록을 나타내는 함수 코드에 사용되는 변수 이름.
connection 모니터링 중인 Azure Cosmos DB 계정에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 자세한 내용은 연결을 참조하세요.
databaseName 컨테이너가 모니터링되는 Azure Cosmos DB 데이터베이스의 이름입니다.
containerName 모니터링되는 컨테이너의 이름입니다.
leaseConnection (선택 사항) 임대 컨테이너를 보유한 Azure Cosmos DB 계정에 연결하는 방법을 지정하는 앱 설정 또는 설정 컨테이너의 이름입니다.

설정하지 않으면 connection 값이 사용됩니다. 이 매개 변수는 포털에서 바인딩이 생성될 때 자동으로 설정됩니다. 임대 컨테이너에 대한 연결 문자열에 쓰기 권한이 있어야 합니다.
leaseDatabaseName (선택 사항) 임대를 저장하는 데 사용되는 컨테이너를 보유하는 데이터베이스의 이름입니다. 설정하지 않으면 databaseName 설정 값이 사용됩니다.
leaseContainerName (선택 사항) 임대를 저장하는 데 사용되는 컨테이너의 이름입니다. 설정하지 않으면 leases 값이 사용됩니다.
createLeaseContainerIfNotExists (선택 사항) true로 설정하면 임대 컨테이너가 아직 없는 경우 자동으로 생성됩니다. 기본값은 false입니다. 값을 true로 설정하면 Microsoft Entra ID를 사용하는 경우 컨테이너 만들기는 허용되는 작업이 아니며 함수를 시작할 수 없습니다.
leasesContainerThroughput (선택 사항) 임대 컨테이너가 생성될 때 할당할 요청 단위의 수를 정의합니다. 이 설정은 createLeaseContainerIfNotExiststrue로 설정된 경우에만 사용됩니다. 이 매개 변수는 포털을 사용하여 바인딩이 생성될 때 자동으로 설정됩니다.
leaseContainerPrefix (선택 사항) 설정하면 이 함수에 대한 임대 컨테이너에서 만든 임대에 접두사로 값이 추가됩니다. 접두사 사용에서는 두 개의 별도 Azure Functions가 서로 다른 접두사로 동일한 임대 컨테이너를 공유할 수 있습니다.
feedPollDelay (선택 사항) 현재 변경 내용이 모두 삭제된 후에 피드에 대한 새로운 변경 내용의 파티션을 폴링하는 작업 간의 지연 시간(밀리초)입니다. 기본값은 5,000밀리초 또는 5초입니다.
leaseAcquireInterval (선택 사항) 설정하면 파티션이 알려진 호스트 인스턴스 간에 균등하게 배포되는지를 계산하는 태스크를 시작하는 간격을 밀리초로 정의합니다. 기본값은 13000(13초)입니다.
leaseExpirationInterval (선택 사항) 설정하면 파티션을 나타내는 임대에 대한 임대 기간인 간격을 밀리초로 정의합니다. 이 간격 내에서 임대를 갱신하지 않으면 기간이 만료되어 다른 인스턴스로 파티션 소유권이 이동합니다. 기본값은 60000(60초)입니다.
leaseRenewInterval (선택 사항) 설정하면 인스턴스가 현재 보유한 파티션의 모든 임대에 대한 갱신 간격을 밀리초로 정의합니다. 기본값은 17000(17초)입니다.
maxItemsPerInvocation (선택 사항) 설정하면 이 속성은 함수 호출당 수신되는 최대 항목 수를 설정합니다. 모니터링되는 컨테이너의 작업이 저장 프로시저를 통해 수행되는 경우 변경 피드에서 항목을 읽을 때 트랜잭션 범위가 유지됩니다. 결과적으로, 수신한 항목 수가 지정된 값보다 높을 수 있어 동일한 트랜잭션에 의해 변경된 항목이 하나의 원자성 일괄 처리의 일부로 반환됩니다.
startFromBeginning (선택 사항) 이 옵션은 트리거에게 현재 시간에 시작하는 대신 컨테이너 변경 기록의 시작 부분에서 변경 내용을 읽도록 지시합니다. 후속 실행에서는 검사점이 이미 저장되어 있으므로 처음부터 읽기는 트리거가 처음 시작될 때만 작동합니다. 임대가 이미 만들어진 후에 이 옵션을 true로 설정하면 아무 효과가 없습니다.
startFromTime (선택 사항) 변경 피드 읽기 작업을 초기화할 날짜와 시간을 가져오거나 설정합니다. 권장되는 형식은 2021-02-16T14:19:29Z와 같은 UTC 지정자가 있는 ISO 8601입니다. 초기 트리거 상태를 설정하는 데만 사용됩니다. 트리거가 임대 상태가 된 후에는 이 값을 변경해도 아무런 효과가 없습니다.
preferredLocations (선택 사항) Azure Cosmos DB 서비스에서 지역 복제된 데이터베이스 계정에 대한 기본 위치(지역)를 정의합니다. 값은 쉼표로 구분해야 합니다. 예를 들면 "미국 동부, 미국 중남부, 북유럽"입니다.

다음 예제에서는 function.json 파일의 Azure Cosmos DB 트리거 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 Azure Cosmos DB 레코드가 추가되거나 수정될 때 로그 메시지를 작성합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseContainerName": "leases",
    "connection": "<connection-app-setting>",
    "databaseName": "Tasks",
    "containerName": "Items",
    "createLeaseContainerIfNotExists": true
}

C# 스크립트 코드는 다음과 같습니다.

    using System;
    using System.Collections.Generic;
    using Microsoft.Extensions.Logging;

    // Customize the model with your own desired properties
    public class ToDoItem
    {
        public string id { get; set; }
        public string Description { get; set; }
    }

    public static void Run(IReadOnlyList<ToDoItem> documents, ILogger log)
    {
      log.LogInformation("Documents modified " + documents.Count);
      log.LogInformation("First document Id " + documents[0].id);
    }

Azure Cosmos DB v2 입력

이 섹션에서는 확장 버전 4.x+에 대한 지원에 대해서만 설명합니다.

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
type cosmosDB로 설정해야 합니다.
direction in로 설정해야 합니다.
이름 변경 사항이 포함된 문서 목록을 나타내는 함수 코드에 사용되는 변수 이름.
connection 모니터링 중인 Azure Cosmos DB 계정에 연결하는 방법을 지정하는 앱 설정 또는 설정 컨테이너의 이름입니다. 자세한 내용은 연결을 참조하세요.
databaseName 컨테이너가 모니터링되는 Azure Cosmos DB 데이터베이스의 이름입니다.
containerName 모니터링되는 컨테이너의 이름입니다.
partitionKey 조회를 위한 파티션 키 값을 지정합니다. 바인딩 매개 변수가 포함될 수 있습니다. 이는 분할된 컨테이너에서 조회 작업을 하는 데 필요합니다.
id 검색할 문서의 ID입니다. 이 속성은 바인딩 식을 지원합니다. idsqlQuery 속성을 모두 설정하지 마세요. 둘 중 하나를 설정하지 않으면 전체 컨테이너가 검색됩니다.
sqlQuery 여러 문서를 검색하는 데 사용되는 Azure Cosmos DB SQL 쿼리입니다. 이 속성은 런타임 바인딩을 지원합니다(예: SELECT * FROM c where c.departmentId = {departmentId}). idsqlQuery 속성을 모두 설정하지 마세요. 둘 중 하나를 설정하지 않으면 전체 컨테이너가 검색됩니다.
preferredLocations (선택 사항) Azure Cosmos DB 서비스에서 지역 복제된 데이터베이스 계정에 대한 기본 위치(지역)를 정의합니다. 값은 쉼표로 구분해야 합니다. 예: East US,South Central US,North Europe.

이 섹션에는 다음 예제가 포함되어 있습니다.

HTTP 트리거 예제에서는 간단한 ToDoItem 형식을 참조합니다.

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}

큐 트리거, 문자열에서 ID 조회

다음 예제에서는 function.json 파일의 Azure Cosmos DB 입력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 단일 문서를 읽고 문서의 텍스트 값을 업데이트합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "inputDocument",
    "type": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "partitionKey": "{partition key value}",
    "connectionStringSetting": "MyAccount_COSMOSDB",
    "direction": "in"
}

C# 스크립트 코드는 다음과 같습니다.

    using System;

    // Change input document contents using Azure Cosmos DB input binding
    public static void Run(string myQueueItem, dynamic inputDocument)
    {
      inputDocument.text = "This has changed.";
    }

큐 트리거, 여러 문서 가져오기, SqlQuery 사용

다음 예제에서는 function.json 파일의 Azure Cosmos DB 입력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 큐 트리거를 사용하여 쿼리 매개 변수를 사용자 지정하여 SQL 쿼리로 지정된 여러 문서를 검색합니다.

큐 트리거는 매개 변수 departmentId를 제공합니다. { "departmentId" : "Finance" }의 큐 메시지는 재무 부서에 대한 모든 레코드를 반환합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "documents",
    "type": "cosmosDB",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connectionStringSetting": "CosmosDBConnection"
}

C# 스크립트 코드는 다음과 같습니다.

    public static void Run(QueuePayload myQueueItem, IEnumerable<dynamic> documents)
    {
        foreach (var doc in documents)
        {
            // operate on each document
        }
    }

    public class QueuePayload
    {
        public string departmentId { get; set; }
    }

HTTP 트리거, 쿼리 문자열에서 ID 조회

다음 예제에서는 단일 문서를 검색하는 C# 스크립트 함수를 보여줍니다. 이 함수는 쿼리 문자열을 사용하여 조회할 ID 및 파티션 키 값을 지정하는 HTTP 요청에 의해 트리거됩니다. 지정된 데이터베이스 및 컬렉션에서 ToDoItem 문서를 검색하는 데 해당 ID와 파티션 키 값이 사용됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}",
      "PartitionKey" : "{Query.partitionKeyValue}"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;
using Microsoft.Extensions.Logging;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
         log.LogInformation($"ToDo item not found");
    }
    else
    {
        log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 경로 데이터에서 ID 조회

다음 예제에서는 단일 문서를 검색하는 C# 스크립트 함수를 보여줍니다. 이 함수는 경로 데이터를 사용하여 조회할 ID 및 파티션 키 값을 지정하는 HTTP 요청에 의해 트리거됩니다. 지정된 데이터베이스 및 컬렉션에서 ToDoItem 문서를 검색하는 데 해당 ID와 파티션 키 값이 사용됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ],
      "route":"todoitems/{partitionKeyValue}/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "id": "{id}",
      "partitionKey": "{partitionKeyValue}"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;
using Microsoft.Extensions.Logging;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
         log.LogInformation($"ToDo item not found");
    }
    else
    {
        log.LogInformation($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 여러 문서 가져오기, SqlQuery 사용

다음 예제에서는 문서 목록을 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 HTTP 요청에 의해 트리거됩니다. 쿼리는 SqlQuery 특성 속성에 지정됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItems",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "in",
      "sqlQuery": "SELECT top 2 * FROM c order by c._ts desc"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;
using Microsoft.Extensions.Logging;

public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<ToDoItem> toDoItems, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    foreach (ToDoItem toDoItem in toDoItems)
    {
        log.LogInformation(toDoItem.Description);
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 여러 문서 가져오기, DocumentClient 사용

다음 예제에서는 문서 목록을 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 HTTP 요청에 의해 트리거됩니다. 코드를 Azure Cosmos DB 바인딩에 의해 제공된 DocumentClient 인스턴스를 사용하여 문서 목록을 읽습니다. DocumentClient 인스턴스는 쓰기 작업에 사용될 수도 있습니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "client",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "inout"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.Documents.Client"

using System.Net;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Extensions.Logging;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, DocumentClient client, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
    string searchterm = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
        .Value;

    if (searchterm == null)
    {
        return req.CreateResponse(HttpStatusCode.NotFound);
    }

    log.LogInformation($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
    IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
        .Where(p => p.Description.Contains(searchterm))
        .AsDocumentQuery();

    while (query.HasMoreResults)
    {
        foreach (ToDoItem result in await query.ExecuteNextAsync())
        {
            log.LogInformation(result.Description);
        }
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

Azure Cosmos DB v2 출력

이 섹션에서는 확장 버전 4.x+에 대한 지원에 대해서만 설명합니다.

다음 표에서는 function.json 파일에 설정된 바인딩 구성 속성을 설명합니다.

function.json 속성 설명
connection 모니터링 중인 Azure Cosmos DB 계정에 연결하는 방법을 지정하는 앱 설정 또는 설정 컬렉션의 이름입니다. 자세한 내용은 연결을 참조하세요.
databaseName 컨테이너가 모니터링되는 Azure Cosmos DB 데이터베이스의 이름입니다.
containerName 모니터링되는 컨테이너의 이름입니다.
createIfNotExists 컨테이너가 존재하지 않을 때 만들어지는지 여부를 나타내는 부울 값입니다. 예약된 처리량으로 새 컨테이너가 만들어지고 비용에 영향을 미치므로 기본값은 false입니다. 자세한 내용은 가격 책정 페이지를 참조하십시오.
partitionKey createIfNotExists이 true이면 만들어진 컨테이너의 파티션 키 경로를 정의합니다. 바인딩 매개 변수가 포함될 수 있습니다.
containerThroughput createIfNotExists가 true이면 만들어진 컨테이너의 처리량을 정의합니다.
preferredLocations (선택 사항) Azure Cosmos DB 서비스에서 지역 복제된 데이터베이스 계정에 대한 기본 위치(지역)를 정의합니다. 값은 쉼표로 구분해야 합니다. 예: East US,South Central US,North Europe.

이 섹션에는 다음 예제가 포함되어 있습니다.

큐 트리거, 하나의 문서 쓰기

다음 예제에서는 function.json 파일의 Azure Cosmos DB 출력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 다음 형식으로 JSON을 수신하는 큐에 대한 큐 입력 바인딩을 사용합니다.

{
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

이 함수는 각 레코드에 대해 다음과 같은 형식의 Azure Cosmos DB 문서를 만듭니다.

{
    "id": "John Henry-123456",
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "employeeDocument",
    "type": "cosmosDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connectionStringSetting": "MyAccount_COSMOSDB",
    "direction": "out"
}

C# 스크립트 코드는 다음과 같습니다.

    #r "Newtonsoft.Json"

    using Microsoft.Azure.WebJobs.Host;
    using Newtonsoft.Json.Linq;
    using Microsoft.Extensions.Logging;

    public static void Run(string myQueueItem, out object employeeDocument, ILogger log)
    {
      log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

      dynamic employee = JObject.Parse(myQueueItem);

      employeeDocument = new {
        id = employee.name + "-" + employee.employeeId,
        name = employee.name,
        employeeId = employee.employeeId,
        address = employee.address
      };
    }

큐 트리거, IAsyncCollector를 사용하여 문서 쓰기

여러 문서를 만들려면 ICollector<T> 또는 IAsyncCollector<T>에 바인딩할 수 있으며, 여기서 T는 지원되는 형식 중 하나입니다.

이 예제에서는 간단한 ToDoItem 형식을 참조합니다.

namespace CosmosDBSamplesV2
{
    public class ToDoItem
    {
        public string id { get; set; }
        public string Description { get; set; }
    }
}

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "name": "toDoItemsIn",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "todoqueueforwritemulti",
      "connectionStringSetting": "AzureWebJobsStorage"
    },
    {
      "type": "cosmosDB",
      "name": "toDoItemsOut",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connectionStringSetting": "CosmosDBConnection",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System;
using Microsoft.Extensions.Logging;

public static async Task Run(ToDoItem[] toDoItemsIn, IAsyncCollector<ToDoItem> toDoItemsOut, ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

    foreach (ToDoItem toDoItem in toDoItemsIn)
    {
        log.LogInformation($"Description={toDoItem.Description}");
        await toDoItemsOut.AddAsync(toDoItem);
    }
}

Azure Cosmos DB v1 트리거

다음 예제에서는 function.json 파일의 Azure Cosmos DB 트리거 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 Azure Cosmos DB 레코드가 수정될 때 로그 메시지를 작성합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "type": "cosmosDBTrigger",
    "name": "documents",
    "direction": "in",
    "leaseCollectionName": "leases",
    "connectionStringSetting": "<connection-app-setting>",
    "databaseName": "Tasks",
    "collectionName": "Items",
    "createLeaseCollectionIfNotExists": true
}

C# 스크립트 코드는 다음과 같습니다.

    #r "Microsoft.Azure.Documents.Client"
    
    using System;
    using Microsoft.Azure.Documents;
    using System.Collections.Generic;
    

    public static void Run(IReadOnlyList<Document> documents, TraceWriter log)
    {
        log.Info("Documents modified " + documents.Count);
        log.Info("First document Id " + documents[0].Id);
    }

Azure Cosmos DB v1 입력

이 섹션에는 다음 예제가 포함되어 있습니다.

HTTP 트리거 예제에서는 간단한 ToDoItem 형식을 참조합니다.

namespace CosmosDBSamplesV1
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}

큐 트리거, 문자열에서 ID 조회

다음 예제에서는 function.json 파일의 Azure Cosmos DB 입력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 단일 문서를 읽고 문서의 텍스트 값을 업데이트합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "inputDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "id" : "{queueTrigger}",
    "partitionKey": "{partition key value}",
    "connection": "MyAccount_COSMOSDB",
    "direction": "in"
}

C# 스크립트 코드는 다음과 같습니다.

    using System;

    // Change input document contents using Azure Cosmos DB input binding
    public static void Run(string myQueueItem, dynamic inputDocument)
    {
        inputDocument.text = "This has changed.";
    }

큐 트리거, 여러 문서 가져오기, SqlQuery 사용

다음 예제에서는 function.json 파일의 Azure Cosmos DB 입력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 큐 트리거를 사용하여 쿼리 매개 변수를 사용자 지정하여 SQL 쿼리로 지정된 여러 문서를 검색합니다.

큐 트리거는 매개 변수 departmentId를 제공합니다. { "departmentId" : "Finance" }의 큐 메시지는 재무 부서에 대한 모든 레코드를 반환합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "documents",
    "type": "documentdb",
    "direction": "in",
    "databaseName": "MyDb",
    "collectionName": "MyCollection",
    "sqlQuery": "SELECT * from c where c.departmentId = {departmentId}",
    "connection": "CosmosDBConnection"
}

C# 스크립트 코드는 다음과 같습니다.

    public static void Run(QueuePayload myQueueItem, IEnumerable<dynamic> documents)
    {
        foreach (var doc in documents)
        {
            // operate on each document
        }
    }

    public class QueuePayload
    {
        public string departmentId { get; set; }
    }

HTTP 트리거, 쿼리 문자열에서 ID 조회

다음 예제에서는 단일 문서를 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 조회할 ID를 지정하기 위해 쿼리 문자열을 사용하는 HTTP 요청에 의해 트리거됩니다. ID는 지정된 데이터베이스 및 컬렉션에서 ToDoItem 문서를 검색하는 데 사용됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{Query.id}"
    }
  ],
  "disabled": true
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
        log.Info($"ToDo item not found");
    }
    else
    {
        log.Info($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 경로 데이터에서 ID 조회

다음 예제에서는 단일 문서를 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 조회할 ID를 지정하기 위해 경로 데이터를 사용하는 HTTP 요청에 의해 트리거됩니다. ID는 지정된 데이터베이스 및 컬렉션에서 ToDoItem 문서를 검색하는 데 사용됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ],
      "route":"todoitems/{id}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItem",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "Id": "{id}"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, ToDoItem toDoItem, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    if (toDoItem == null)
    {
        log.Info($"ToDo item not found");
    }
    else
    {
        log.Info($"Found ToDo item, Description={toDoItem.Description}");
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 여러 문서 가져오기, SqlQuery 사용

다음 예제에서는 문서 목록을 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 HTTP 요청에 의해 트리거됩니다. 쿼리는 SqlQuery 특성 속성에 지정됩니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "toDoItems",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "in",
      "sqlQuery": "SELECT top 2 * FROM c order by c._ts desc"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<ToDoItem> toDoItems, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    foreach (ToDoItem toDoItem in toDoItems)
    {
        log.Info(toDoItem.Description);
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

HTTP 트리거, 여러 문서 가져오기, DocumentClient 사용

다음 예제에서는 문서 목록을 검색하는 C# 스크립트 함수를 보여줍니다. 함수는 HTTP 요청에 의해 트리거됩니다. 코드를 Azure Cosmos DB 바인딩에 의해 제공된 DocumentClient 인스턴스를 사용하여 문서 목록을 읽습니다. DocumentClient 인스턴스는 쓰기 작업에 사용될 수도 있습니다.

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "client",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "inout"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.Documents.Client"

using System.Net;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, DocumentClient client, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    Uri collectionUri = UriFactory.CreateDocumentCollectionUri("ToDoItems", "Items");
    string searchterm = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "searchterm", true) == 0)
        .Value;

    if (searchterm == null)
    {
        return req.CreateResponse(HttpStatusCode.NotFound);
    }

    log.Info($"Searching for word: {searchterm} using Uri: {collectionUri.ToString()}");
    IDocumentQuery<ToDoItem> query = client.CreateDocumentQuery<ToDoItem>(collectionUri)
        .Where(p => p.Description.Contains(searchterm))
        .AsDocumentQuery();

    while (query.HasMoreResults)
    {
        foreach (ToDoItem result in await query.ExecuteNextAsync())
        {
            log.Info(result.Description);
        }
    }
    return req.CreateResponse(HttpStatusCode.OK);
}

Azure Cosmos DB v1 출력

이 섹션에는 다음 예제가 포함되어 있습니다.

  • 큐 트리거, 하나의 문서 쓰기
  • 큐 트리거, IAsyncCollector를 사용하여 문서 쓰기

큐 트리거, 하나의 문서 쓰기

다음 예제에서는 function.json 파일의 Azure Cosmos DB 출력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 다음 형식으로 JSON을 수신하는 큐에 대한 큐 입력 바인딩을 사용합니다.

{
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

이 함수는 각 레코드에 대해 다음과 같은 형식의 Azure Cosmos DB 문서를 만듭니다.

{
    "id": "John Henry-123456",
    "name": "John Henry",
    "employeeId": "123456",
    "address": "A town nearby"
}

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "name": "employeeDocument",
    "type": "documentDB",
    "databaseName": "MyDatabase",
    "collectionName": "MyCollection",
    "createIfNotExists": true,
    "connection": "MyAccount_COSMOSDB",
    "direction": "out"
}

C# 스크립트 코드는 다음과 같습니다.

    #r "Newtonsoft.Json"

    using Microsoft.Azure.WebJobs.Host;
    using Newtonsoft.Json.Linq;

    public static void Run(string myQueueItem, out object employeeDocument, TraceWriter log)
    {
        log.Info($"C# Queue trigger function processed: {myQueueItem}");

        dynamic employee = JObject.Parse(myQueueItem);

        employeeDocument = new {
            id = employee.name + "-" + employee.employeeId,
            name = employee.name,
            employeeId = employee.employeeId,
            address = employee.address
        };
    }

큐 트리거, IAsyncCollector를 사용하여 문서 쓰기

여러 문서를 만들려면 ICollector<T> 또는 IAsyncCollector<T>에 바인딩할 수 있으며, 여기서 T는 지원되는 형식 중 하나입니다.

이 예제에서는 간단한 ToDoItem 형식을 참조합니다.

namespace CosmosDBSamplesV1
{
    public class ToDoItem
    {
        public string Id { get; set; }
        public string Description { get; set; }
    }
}

function.json 파일은 다음과 같습니다.

{
  "bindings": [
    {
      "name": "toDoItemsIn",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "todoqueueforwritemulti",
      "connection": "AzureWebJobsStorage"
    },
    {
      "type": "documentDB",
      "name": "toDoItemsOut",
      "databaseName": "ToDoItems",
      "collectionName": "Items",
      "connection": "CosmosDBConnection",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# 스크립트 코드는 다음과 같습니다.

using System;

public static async Task Run(ToDoItem[] toDoItemsIn, IAsyncCollector<ToDoItem> toDoItemsOut, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed {toDoItemsIn?.Length} items");

    foreach (ToDoItem toDoItem in toDoItemsIn)
    {
        log.Info($"Description={toDoItem.Description}");
        await toDoItemsOut.AddAsync(toDoItem);
    }
}

Azure SQL 트리거

Azure SQL 트리거에 대한 더 많은 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

예는 ToDoItem 클래스와 해당 데이터베이스 테이블을 참조하세요.

namespace AzureSQL.ToDo
{
    public class ToDoItem
    {
        public Guid Id { get; set; }
        public int? order { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public bool? completed { get; set; }
    }
}
CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

변경 내용 추적은 데이터베이스 및 테이블에서 사용하도록 설정됩니다.

ALTER DATABASE [SampleDatabase]
SET CHANGE_TRACKING = ON
(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON);

ALTER TABLE [dbo].[ToDo]
ENABLE CHANGE_TRACKING;

SQL 트리거는 각각 두 가지 속성이 있는 SqlChange 개체 목록인 IReadOnlyList<SqlChange<T>>에 바인딩됩니다.

  • 항목: 변경된 항목입니다. 항목의 형식은 ToDoItem 클래스에 표시된 대로 테이블 스키마를 따라야 합니다.
  • 작업:SqlChangeOperation 열거형의 값입니다. 가능한 값은 Insert, UpdateDelete입니다.

다음 예에서는 function.json 파일의 SQL 트리거와 ToDo 테이블이 변경될 때 호출되는 C# 스크립트 함수를 보여 줍니다.

다음은 function.json 파일의 바인딩 데이터입니다.

{
    "name": "todoChanges",
    "type": "sqlTrigger",
    "direction": "in",
    "tableName": "dbo.ToDo",
    "connectionStringSetting": "SqlConnectionString"
}

다음은 C# 스크립트 함수입니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static void Run(IReadOnlyList<SqlChange<ToDoItem>> todoChanges, ILogger log)
{
    log.LogInformation($"C# SQL trigger function processed a request.");

    foreach (SqlChange<ToDoItem> change in todoChanges)
    {
        ToDoItem toDoItem = change.Item;
        log.LogInformation($"Change operation: {change.Operation}");
        log.LogInformation($"Id: {toDoItem.Id}, Title: {toDoItem.title}, Url: {toDoItem.url}, Completed: {toDoItem.completed}");
    }
}

Azure SQL 입력

Azure SQL 입력 바인딩에 대한 더 많은 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

예는 ToDoItem 클래스와 해당 데이터베이스 테이블을 참조하세요.

namespace AzureSQL.ToDo
{
    public class ToDoItem
    {
        public Guid Id { get; set; }
        public int? order { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public bool? completed { get; set; }
    }
}
CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP 트리거, 쿼리 문자열에서 ID별 행 가져오기

다음 예제에서는 function.json 파일의 Azure SQL 입력 바인딩 및 해당 바인딩을 사용하는 C# 스크립트 함수를 보여 줍니다. 이 함수는 쿼리 문자열을 사용하여 ID를 지정하는 HTTP 요청에 의해 트리거됩니다. 해당 ID는 지정된 쿼리로 ToDoItem 레코드를 쿼리하는 데 사용됩니다.

참고 항목

HTTP 쿼리 문자열 매개 변수는 대/소문자를 구분합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItem",
    "type": "sql",
    "direction": "in",
    "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",
    "commandType": "Text",
    "parameters": "@Id = {Query.id}",
    "connectionStringSetting": "SqlConnectionString"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Collections.Generic;

public static IActionResult Run(HttpRequest req, ILogger log, IEnumerable<ToDoItem> todoItem)
{
    return new OkObjectResult(todoItem);
}

HTTP 트리거, 행 삭제

다음 예제에서는 function.json 파일의 Azure SQL 입력 바인딩과 바인딩을 사용하여 HTTP 요청 쿼리 매개 변수의 입력으로 저장 프로시저를 실행하는 C# 스크립트 함수를 보여줍니다. 이 예에서 저장 프로시저는 매개 변수 값에 따라 단일 레코드 또는 모든 레코드를 삭제합니다.

저장 프로시저 dbo.DeleteToDo는 SQL 데이터베이스에 만들어져야 합니다.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItems",
    "type": "sql",
    "direction": "in",
    "commandText": "DeleteToDo",
    "commandType": "StoredProcedure",
    "parameters": "@Id = {Query.id}",
    "connectionStringSetting": "SqlConnectionString"
}
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace AzureSQL.ToDo
{
    public static class DeleteToDo
    {
        // delete all items or a specific item from querystring
        // returns remaining items
        // uses input binding with a stored procedure DeleteToDo to delete items and return remaining items
        [FunctionName("DeleteToDo")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "DeleteFunction")] HttpRequest req,
            ILogger log,
            [Sql(commandText: "DeleteToDo", commandType: System.Data.CommandType.StoredProcedure, 
                parameters: "@Id={Query.id}", connectionStringSetting: "SqlConnectionString")] 
                IEnumerable<ToDoItem> toDoItems)
        {
            return new OkObjectResult(toDoItems);
        }
    }
}

C# 스크립트 코드는 다음과 같습니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Collections.Generic;

public static IActionResult Run(HttpRequest req, ILogger log, IEnumerable<ToDoItem> todoItems)
{
    return new OkObjectResult(todoItems);
}

Azure SQL 출력

Azure SQL 출력 바인딩에 대한 더 많은 샘플은 GitHub 리포지토리에서 사용할 수 있습니다.

이 섹션에는 다음 예제가 포함되어 있습니다.

예는 ToDoItem 클래스와 해당 데이터베이스 테이블을 참조하세요.

namespace AzureSQL.ToDo
{
    public class ToDoItem
    {
        public Guid Id { get; set; }
        public int? order { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public bool? completed { get; set; }
    }
}
CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP 트리거, 테이블에 레코드 쓰기

다음 예에서는 HTTP POST 요청에 제공된 데이터를 JSON 본문으로 사용하여 테이블에 레코드를 추가하는 C# 스크립트 함수와 function.json 파일의 SQL 출력 바인딩을 보여 줍니다.

다음은 function.json 파일의 바인딩 데이터입니다.

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "post"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItem",
    "type": "sql",
    "direction": "out",
    "commandText": "dbo.ToDo",
    "connectionStringSetting": "SqlConnectionString"
}

다음은 샘플 C# 스크립트 코드입니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static IActionResult Run(HttpRequest req, ILogger log, out ToDoItem todoItem)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = new StreamReader(req.Body).ReadToEnd();
    todoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);

    return new OkObjectResult(todoItem);
}

HTTP 트리거, 두 테이블에 쓰기

다음 예에서는 HTTP POST 요청에 제공된 데이터를 JSON 본문 및 다중 출력 바인딩으로 사용하여 두 개의 서로 다른 테이블(dbo.ToDodbo.RequestLog)의 데이터베이스에 레코드를 추가하는 C# 스크립트 함수와 function.json 파일의 SQL 출력 바인딩을 보여 줍니다.

두 번째 테이블 dbo.RequestLog는 다음 정의에 해당합니다.

CREATE TABLE dbo.RequestLog (
    Id int identity(1,1) primary key,
    RequestTimeStamp datetime2 not null,
    ItemCount int not null
)

다음은 function.json 파일의 바인딩 데이터입니다.

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "post"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItem",
    "type": "sql",
    "direction": "out",
    "commandText": "dbo.ToDo",
    "connectionStringSetting": "SqlConnectionString"
},
{
    "name": "requestLog",
    "type": "sql",
    "direction": "out",
    "commandText": "dbo.RequestLog",
    "connectionStringSetting": "SqlConnectionString"
}

다음은 샘플 C# 스크립트 코드입니다.

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static IActionResult Run(HttpRequest req, ILogger log, out ToDoItem todoItem, out RequestLog requestLog)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = new StreamReader(req.Body).ReadToEnd();
    todoItem = JsonConvert.DeserializeObject<ToDoItem>(requestBody);

    requestLog = new RequestLog();
    requestLog.RequestTimeStamp = DateTime.Now;
    requestLog.ItemCount = 1;

    return new OkObjectResult(todoItem);
}

public class RequestLog {
    public DateTime RequestTimeStamp { get; set; }
    public int ItemCount { get; set; }
}

RabbitMQ 출력

다음 예제에서는 function.json 파일의 RabbitMQ 출력 바인딩과 바인딩을 사용하는 C# 스크립트 함수를 보여줍니다. 함수는 HTTP 트리거에서 메시지를 읽고 RabbitMQ 큐에 출력합니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "bindings": [
        {
            "type": "httpTrigger",
            "direction": "in",
            "authLevel": "function",
            "name": "input",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "type": "rabbitMQ",
            "name": "outputMessage",
            "queueName": "outputQueue",
            "connectionStringSetting": "rabbitMQConnectionAppSetting",
            "direction": "out"
        }
    ]
}

C# 스크립트 코드는 다음과 같습니다.

using System;
using Microsoft.Extensions.Logging;

public static void Run(string input, out string outputMessage, ILogger log)
{
    log.LogInformation(input);
    outputMessage = input;
}

SendGrid 출력

다음 예에서는 function.json 파일의 SendGrid 출력 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여줍니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

{
    "bindings": [
        {
          "type": "queueTrigger",
          "name": "mymsg",
          "queueName": "myqueue",
          "connection": "AzureWebJobsStorage",
          "direction": "in"
        },
        {
          "type": "sendGrid",
          "name": "$return",
          "direction": "out",
          "apiKey": "SendGridAPIKeyAsAppSetting",
          "from": "{FromEmail}",
          "to": "{ToEmail}"
        }
    ]
}

C# 스크립트 코드는 다음과 같습니다.

#r "SendGrid"

using System;
using SendGrid.Helpers.Mail;
using Microsoft.Azure.WebJobs.Host;

public static SendGridMessage Run(Message mymsg, ILogger log)
{
    SendGridMessage message = new SendGridMessage()
    {
        Subject = $"{mymsg.Subject}"
    };
    
    message.AddContent("text/plain", $"{mymsg.Content}");

    return message;
}
public class Message
{
    public string ToEmail { get; set; }
    public string FromEmail { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}

SignalR 트리거

function.json 파일의 예제 바인딩 데이터는 다음과 같습니다.

{
    "type": "signalRTrigger",
    "name": "invocation",
    "hubName": "SignalRTest",
    "category": "messages",
    "event": "SendMessage",
    "parameterNames": [
        "message"
    ],
    "direction": "in"
}

그리고 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using System;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Microsoft.Extensions.Logging;

public static void Run(InvocationContext invocation, string message, ILogger logger)
{
    logger.LogInformation($"Receive {message} from {invocationContext.ConnectionId}.");
}

SignalR 입력

다음 예에서는 function.json 파일의 SignalR 연결 정보 입력 바인딩 및 바인딩을 사용하여 연결 정보를 반환하는 C# Script 함수를 보여줍니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

예제 function.json:

{
    "type": "signalRConnectionInfo",
    "name": "connectionInfo",
    "hubName": "chat",
    "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
    "direction": "in"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static SignalRConnectionInfo Run(HttpRequest req, SignalRConnectionInfo connectionInfo)
{
    return connectionInfo;
}

바인딩 식을 사용하여 바인딩의 userId 속성을 {headers.x-ms-client-principal-id} 또는 {headers.x-ms-client-principal-name} 헤더 중 하나의 값으로 설정할 수 있습니다.

예제 function.json:

{
    "type": "signalRConnectionInfo",
    "name": "connectionInfo",
    "hubName": "chat",
    "userId": "{headers.x-ms-client-principal-id}",
    "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
    "direction": "in"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static SignalRConnectionInfo Run(HttpRequest req, SignalRConnectionInfo connectionInfo)
{
    // connectionInfo contains an access key token with a name identifier
    // claim set to the authenticated user
    return connectionInfo;
}

SignalR 출력

function.json 파일의 바인딩 데이터는 다음과 같습니다.

예제 function.json:

{
  "type": "signalR",
  "name": "signalRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static Task Run(
    object message,
    IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

SignalR 메시지에서 ‘user ID’ 속성을 설정하여 사용자에게 인증된 연결에만 메시지를 보낼 수 있습니다.

예제 function.json:

{
  "type": "signalR",
  "name": "signalRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static Task Run(
    object message,
    IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            // the message will only be sent to this user ID
            UserId = "userId1",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

SignalR 메시지에서 그룹 이름 설정하여 그룹에 추가된 연결에만 메시지를 보낼 수 있습니다.

예제 function.json:

{
  "type": "signalR",
  "name": "signalRMessages",
  "hubName": "<hub_name>",
  "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
  "direction": "out"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static Task Run(
    object message,
    IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage
        {
            // the message will be sent to the group with this name
            GroupName = "myGroup",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

SignalR Service를 사용하면 사용자 또는 연결을 그룹에 추가할 수 있습니다. 그런 다음, 메시지를 그룹으로 보낼 수 있습니다. SignalR 출력 바인딩을 사용하여 그룹을 관리할 수 있습니다.

다음 예제에서는 그룹에 사용자를 추가합니다.

예제 function.json

{
    "type": "signalR",
    "name": "signalRGroupActions",
    "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
    "hubName": "chat",
    "direction": "out"
}

Run.csx

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static Task Run(
    HttpRequest req,
    ClaimsPrincipal claimsPrincipal,
    IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
    var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
    return signalRGroupActions.AddAsync(
        new SignalRGroupAction
        {
            UserId = userIdClaim.Value,
            GroupName = "myGroup",
            Action = GroupAction.Add
        });
}

다음 예제에서는 그룹에서 사용자를 제거합니다.

예제 function.json

{
    "type": "signalR",
    "name": "signalRGroupActions",
    "connectionStringSetting": "<name of setting containing SignalR Service connection string>",
    "hubName": "chat",
    "direction": "out"
}

Run.csx

#r "Microsoft.Azure.WebJobs.Extensions.SignalRService"
using Microsoft.Azure.WebJobs.Extensions.SignalRService;

public static Task Run(
    HttpRequest req,
    ClaimsPrincipal claimsPrincipal,
    IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
    var userIdClaim = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier);
    return signalRGroupActions.AddAsync(
        new SignalRGroupAction
        {
            UserId = userIdClaim.Value,
            GroupName = "myGroup",
            Action = GroupAction.Remove
        });
}

Twilio 출력

다음 예에서는 function.json 파일의 Twilio 출력 바인딩 및 바인딩을 사용하는 C# 스크립트 함수를 보여줍니다. 이 함수는 out 매개 변수를 사용하여 문자 메시지를 보냅니다.

function.json 파일의 바인딩 데이터는 다음과 같습니다.

예제 function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

C# 스크립트 코드는 다음과 같습니다.

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static void Run(string myQueueItem, out CreateMessageOptions message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    message = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    message.Body = msg;
}

Out 매개 변수는 비동기 코드에서 사용할 수 없습니다. 비동기 C# 스크립트 코드 예제는 다음과 같습니다.

#r "Newtonsoft.Json"
#r "Twilio"
#r "Microsoft.Azure.WebJobs.Extensions.Twilio"

using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;

public static async Task Run(string myQueueItem, IAsyncCollector<CreateMessageOptions> message,  ILogger log)
{
    log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    dynamic order = JsonConvert.DeserializeObject(myQueueItem);
    string msg = "Hello " + order.name + ", thank you for your order.";

    // You must initialize the CreateMessageOptions variable with the "To" phone number.
    CreateMessageOptions smsText = new CreateMessageOptions(new PhoneNumber("+1704XXXXXXX"));

    // A dynamic message can be set instead of the body in the output binding. In this example, we use
    // the order information to personalize a text message.
    smsText.Body = msg;

    await message.AddAsync(smsText);
}

준비 트리거

다음 예는 function.json 파일의 준비 트리거와 앱에 추가될 때 각각의 새 인스턴스에서 실행되는 C# 스크립트 함수를 보여 줍니다.

Functions 런타임 버전 1.x에서는 지원되지 않습니다.

function.json 파일은 다음과 같습니다.

{
    "bindings": [
        {
            "type": "warmupTrigger",
            "direction": "in",
            "name": "warmupContext"
        }
    ]
}
public static void Run(WarmupContext warmupContext, ILogger log)
{
    log.LogInformation("Function App instance is warm.");  
}

다음 단계