Search code examples
c#azureazure-functionsazure-data-factory

HTTP Trigger using octet stream


Is it possible to create an Azure Functions HTTP trigger that uses application/octet-stream instead of application/json?

I currently have a trigger that for application/json.


Solution

  • In order to stream the data in HTTP Trigger as stream:-

    According to this Github document, You can edit your function.json file of your HTTP Trigger with data type as binary or stream to stream the data like below:-

    function.json code:-

    {
    
    "generatedBy": "Microsoft.NET.Sdk.Functions.Generator-4.1.1",
    
    "configurationSource": "attributes",
    
    "bindings": [
    
    {
    
    "type": "httpTrigger",
    
    "direction": "in",
    
    "dataType": "stream",
    
    "route": "myroute",
    
    "methods": [
    
    "post"
    
    ],
    
    "authLevel": "function",
    
    "name": "req"
    
    }
    
    ],
    
    "disabled": false,
    
    "scriptFile": "../bin/FunctionApp9.dll",
    
    "entryPoint": "MyFunction.RunAsync"
    
    }
    

    enter image description here

    Additionally according to this SO Thread answer by Andy, By referring Andy's code, I got the below output in my browser after I ran the HTTP trigger:- Here response.ContentType is set to "application/json-data-stream";

    Andy's Code:- Function.cs:-

    using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using
    Microsoft.Azure.WebJobs.Extensions.Http; using
    Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using
    Newtonsoft.Json; using System.Collections.Generic;
    
    namespace FunctionApp10 {
        public class Function1
        {
            private async IAsyncEnumerable<string> GetDataAsync()
            {
                for (var i = 0; i < 100; ++i)
                {
                    yield return "{\"hello\":\"world\"}";
                }
            }
    
            [FunctionName("Function1")]
            public async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                ILogger log)
            {
                var response = req.HttpContext.Response;
    
                await using var sw = new StreamWriter(response.Body);
                await foreach (var msg in GetDataAsync())
                {
                    await sw.WriteLineAsync(msg);
                }
    
                await sw.FlushAsync();
    
                response.StatusCode = 200;
                response.ContentType = "application/json-data-stream";
    
                return new EmptyResult();
            }
        }
      } 
    

    Output:- Trigger got executed:-

    enter image description here

    Got streamed response in the Browser like below:-

    enter image description here