我需要验证进入我的 Azure http 函数的内容是否不为空且类型为 JSON。
所以我在我的 Azure 函数中执行此操作:
if (req.Body.Length == 0)
{
var nullresponse = req.CreateResponse(HttpStatusCode.BadRequest);
return nullresponse;
我想检查它是否也是 JSON 类型 - 知道如何做到这一点吗?
req
是 HttpRequestData 类型,按照隔离函数的正常情况。
是的,您需要检查
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;
}
我已经在我的环境中重现了,以下是我的预期结果:
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 :
If Invalid Json:
If Valid Json: