从 Azure Function 中的请求 (httpRequestData) 获取内容类型

问题描述 投票:0回答:2

我需要验证进入我的 Azure http 函数的内容是否不为空且类型为 JSON。

所以我在我的 Azure 函数中执行此操作:

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

我想检查它是否也是 JSON 类型 - 知道如何做到这一点吗?

req
是 HttpRequestData 类型,按照隔离函数的正常情况。

c# azure-functions http-status-codes azure-functions-isolated
2个回答
1
投票

是的,您需要检查

Content-Type
是否是
application/json
或不是如下所示。也请注意
HttpStatusCode.UnsupportedMediaType

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;
}

0
投票

我已经在我的环境中重现了,以下是我的预期结果:

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

© www.soinside.com 2019 - 2024. All rights reserved.