如何在 azure 函数中访问 http 请求的所有字段(在 C# 中解析 JSON)? [英] How I can access all fields of a http-request in an azure function (parse JSON in C#)?
问题描述
microsoft azure 对我来说是一个全新的编程主题.编程基础语言是 C#.我必须使用逻辑应用程序中的 Azure 函数 Http 触发器(当新电子邮件到达时).我将日志应用程序中传入电子邮件中的所有可能数据提供给到 azure 函数调用.
The microsoft azure is for me complete new programming topic. Programming base language is C#. I have to use Azure Funtion Http trigger from logic App (when new e-mail arrive). I give all possible data from the incoming e-mail in the log app to to the azure function call.
然后我首先遇到的问题是 HttpRequest 请求中没有任何内容(没有数据).
Then I had first the problem nothing (no data) was requestable from the HttpRequest req.
我发现 C# .NetCore3.1 有 JSON-Object 问题并返回 null-object.然后我用 .NetCore2.1 构建了这个项目,它运行正常.我得到了像 req.Host
这样的正确信息,并且在这样的调用之后我在数据中看到了一个有效的 JSON 对象
I found out that C# .NetCore3.1 has problem with JSON-Object and get null-object back.
Then I build the project with .NetCore2.1 and it worked generally.
I get correct informations like req.Host
and i see a vaild JSON-object in data after such a call
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
但我不知道如何解析来自 JSON 对象的数据,例如(来自、到、主题、内容、附件等).
But I don't know how I an parse the data like (from, to, subject, content, attachment,..) from the JSON-object.
我尝试了很多我发现的样本,但我不喜欢任何有用的东西,例如获取空值,异常,..
I have tried many samples i found , but i fond nothing what worked, e.g. get null, exception,..
可以请这里的人发布一个小代码片段,该代码段适用于使用 VS2017/2019 .NetCore2.1 编译的 azure 函数..
Can please someone here post a small code snippet that works for azure function compiled with VS2017/2019 .NetCore2.1..
还有另一个问题是最终有没有办法直接从 http 请求中获取 MimeMessage-obj?然后我可以直接从该对象获取信息,但帮助我解决这两个解决方案之一哪里还好.
And other question is there eventually a way get the MimeMessage-obj direct from the http-request? then i can get the informations direct from that object, but helping me with one of this both solution where fine.
否则我将 JSoN 结构拆分到自己身上,以一种非常尴尬的方式获取信息.所以我希望有人能帮助我.
Otherwise I spilit the the JSoN Structure on myself to get the the informations on a very awkward way. So I hope someone can help me.
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation($" host : {req.Host}");
string name = req.Query["name"];
// read the contents of the posted data into a string
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// use Json.NET to deserialize the posted JSON into a C# dynamic object
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
例如,我有这样一个 Json 内容(在这两行代码之后的 dtaa 中):
For Example i had such a Json-content (is in dtaa after thes 2 lines of code):
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();动态数据 = JsonConvert.DeserializeObject(requestBody);
string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody);
用于解析简短电子邮件的 Json-Content(其他请求可能因更多或更少的参数(字段)而异)
Json-Content for a short email to parse (other request could differn in more ore lesser paramters(fields))
{ {
"Conversion Id": "AAQkADRmZDAwMTMwLTI3MTMtNGI0Ny1iMzFiLTQzYWJiZDY0YWI1ZQAQAE2OZM06t0uQqpd9MuONKNQ=",
"From": "test1@testxyz.com",
"Has Attachment": false,
"Internet Message Id": "<AM0PR07MB44178000A0B37882D6BC01D99ACC0@AM0PR07MB4417.eurprd07.prod.outlook.com>",
"Is Html": false,
"Is rRad": false,
"Message Id": "AAMkADRmZDAwMTMwLTI3MTMtNGI0Ny1iMzFiLTQzYWJiZDY0YWI1ZQBGAAAAAAAvlJZPJxnGS4f6YWxh7zGsBwBnLziSnuG8R6h5C2SVmlYlAAHViSWpAACAWl3JfUo4SI7D5g-MgfEiAAJiPJQeAAA=",
"Received Time": "2020-12-09T14:05:06+00:00",
"Subject": "test1",
"To": "test2@testxyz.com",
"emailBody": "1234
",
"importance": "normal"
}
}
推荐答案
对于这个需求,你需要在你的函数代码中创建一个内部类来将请求体解析为一个对象.请参考我下面的代码:
For this requirement, you need to create an inner class in your function code to parse the request body to an object. Please refer to my code below:
using System;
using System.IO;
using System.Threading.Tasks;
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;
namespace FunctionApp2
{
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
//dynamic data = JsonConvert.DeserializeObject(requestBody);
EmailItem data = JsonConvert.DeserializeObject<EmailItem>(requestBody);
log.LogInformation(data.From);
log.LogInformation(data.Has_Attachment.ToString());
return new OkObjectResult("completed");
}
}
public class EmailItem
{
public string From { get; set; }
public Boolean Has_Attachment { get; set; }
//Add other fields which you want, please note add all of the fields which your request may contains in this inner class.
}
}
正如您提到的其他请求可能在更多或更少的参数(字段)
上有所不同,因此请在 EmailItem
类中添加您的请求可能包含的所有字段.
As you mentioned other request could differn in more ore lesser paramters(fields)
, so please add all of the fields which your request may contains in the EmailItem
class.
顺便说一下,我上面提供的代码是根据您的需要使用 .net core 2.1 进行测试的.但我认为代码也可以在 .net core 3.1 中工作
By the way, the code I provided above was test with .net core 2.1 as you required. But I think the code can also work in .net core 3.1
这篇关于如何在 azure 函数中访问 http 请求的所有字段(在 C# 中解析 JSON)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!