Getting content-type from a request (httpRequestData) in Azure Function

1.7k Views Asked by At

I need to verify if the content coming into my Azure http function is not empty and is of type JSON.

So I am doing this within my Azure function:

 if (req.Body.Length == 0)
            {
                
                var nullresponse = req.CreateResponse(HttpStatusCode.BadRequest);
                return nullresponse;

I want to check if it's type JSON too - any idea on how to do that?

req is type HttpRequestData as per normal on isolated functions.

2

There are 2 best solutions below

0
On

I have reproduced in my environment and below are my expected results:

Code:

using System;
using System.Net;
using Azure;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;

namespace FunctionApp43
{
    public class Function1
    {
        private readonly ILogger _logger;

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

        [Function("Function1")]
        public async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            if (req.Body.Length == 0)
            {

                response.WriteString("Empty Json");
                Console.WriteLine("Empty Json");
                return response;
            }
            else
            {
                try
                {
                    _logger.LogInformation("C# HTTP trigger function processed a request Rithwik.");
                    string rb;
                    using (StreamReader streamReader = new StreamReader(req.Body))
                    {
                        rb = await streamReader.ReadToEndAsync();
                    }

                    var s = JSchema.Parse(rb);
                    var json = JObject.Parse(rb);
                    IList<string> message;
                    bool valid1 = json.IsValid(s, out message);
                    Console.WriteLine(valid1);
                    if (valid1)
                    {
                        Console.WriteLine("It is Valid json Rithwik\n", message);
                    }
                    response.WriteString("Valid Json Rithwik!");

                    return response;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error Invalid Json" + e.Message);
                    response.WriteString("Error Invalid Json Check Console for full Details");
                    return response;
                }
            }

        }
    }
}

Output:

If Empty String :

enter image description here

enter image description here

If Invalid Json:

enter image description here

enter image description here

If Valid Json:

enter image description here

enter image description here

1
On

yes, you need the check whether the Content-Type is application/json or not like below. Pay attention to HttpStatusCode.UnsupportedMediaType also.

if (req.Headers.TryGetValue("Content-Type", out var contentType) &&
    contentType == "application/json")
{
    // Content type is JSON
}
else
{
    var response = req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    return response;
}