如何在azure函数中访问http请求的所有字段(在C#中解析JSON)? [英] How I can access all fields of a http-request in an azure function (parse JSON in C#)?

查看:36
本文介绍了如何在azure函数中访问http请求的所有字段(在C#中解析JSON)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Microsoft Azure对我来说是一个全新的编程主题.编程的基本语言是C#.我必须使用来自逻辑应用程序的Azure Funtion Http触发器(当收到新电子邮件时).我将来自日志应用程序中传入电子邮件的所有可能数据提供给到天蓝色函数调用.

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对象有问题,并返回了空对象.然后,我使用.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.

我尝试了很多发现的样品,但是我不喜欢任何有效的方法,例如获取null,异常,..

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 =等待新的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\r\n",
        "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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆