如何将SQS消息正文解析为JSON?

时间:2018-12-12 23:50:03

标签: c# json asp.net-core json.net amazon-sqs

我正在构建一个使用SQS从队列中获取信息的.NET Core 2.2 Web应用程序。我只想将特定的元素发送到视图,而不是将整个消息输出发送到我的视图。据我了解,NewtonSoft.JSON可以将列表转换为JSON,但不确定如何解析该列表的某些部分。

我的控制器逻辑如下:

public async Task<IActionResult> Index()
    {
        //List<MessageModel> models = new List<MessageModel>();
        MessageModel model = new MessageModel();
        List<MessageModel> models = new List<MessageModel>();
        models = await ListTemplatesAsync(models);

        await StartEnvironmentAsync(models);
        return View(models);
    }

    private async Task<List<MessageModel>> ListTemplatesAsync(List<MessageModel> models)
    {
        var request = await GetEnvironments.GetAWSTemplatesAsync();
        var response = await GetEnvironments.OnMessageReceiptAsync();
        //models = new List<MessageModel>();

        foreach (var msg in response)
        {
            models.Add(new MessageModel(msg.MessageId, msg.Body, msg.MessageAttributes, msg.ReceiptHandle));
            string json = JsonConvert.SerializeObject(models, Formatting.None);
        }

        return models;
    }

我通过以下方法获取MessageModel列表:

 try
        {
            AWSConfigs.LoggingConfig.LogMetrics = false;
            AWSConfigs.LoggingConfig.LogResponses = ResponseLoggingOption.OnError;
            AWSConfigs.LoggingConfig.LogTo = LoggingOptions.Console;
            AWSConfigs.LoggingConfig.LogMetricsFormat = LogMetricsFormatOption.Standard;

            IAmazonSQS client = options.CreateServiceClient<IAmazonSQS>();
            var request =  new ReceiveMessageRequest{};

            List<string> AttributesList = new List<string>
            {
                "sourcemessageId",
                "status",
                "status_message"
            };
            request.MessageAttributeNames = AttributesList;
            request.QueueUrl = recvQueueUrl;
            request.MaxNumberOfMessages = 10;

            ReceiveMessageResponse response = await client.ReceiveMessageAsync(request);

            if (response.HttpStatusCode == HttpStatusCode.Accepted)
            {
                Console.WriteLine("Read Response OK");
            }
            else
            {
                Console.WriteLine("Read Response Failed");
            }

            string FoundHandle = null;

            var messages = response.Messages;
            var list = new List<Message>();

            messages.ForEach(delegate(Message m)
            {
                Console.WriteLine("Read MessageId");
                Console.WriteLine(m.MessageId);
                Console.Write("Body");
                Console.WriteLine(m.Body);
                var curAttributes = m.MessageAttributes;
                var allattrib = curAttributes.GetEnumerator();


                while (allattrib.MoveNext())
                {
                    var pair = allattrib.Current;

                    Console.Write(pair.Key);
                    Console.Write("=");
                    Console.WriteLine(pair.Value.StringValue);
                }

                FoundHandle = m.ReceiptHandle;

            });
            foreach (var message in messages)
            {
                list.Add(message);
            }

            string json = JsonConvert.SerializeObject(list, Formatting.Indented);
            return list;
        }
        catch(AmazonSQSException ex)
        {
            Console.WriteLine(ex.Message);
            throw new AmazonSQSException(ex.Message);
        }

响应主体部分如下:

Message Body
{"Templates": [{"TemplateID": "1", "TemplateName": "Metasploitable3", 
 "TemplateDesc": "Vulnerable Windows 2008 R2 Distribution"},

我的视图现在包含一个简单的HTML表结构,如下所示:

@model IEnumerable<MessageModel>;
    }
<table>
  <thead>
    <tr>
     <th>
       @Html.DisplayNameFor(model => model.Message)
     </th>
     <th>
       @Html.DisplayNameFor(model => model.Body)
     </th>
    </tr>
  </thead>
 <tbody>
    @foreach (var item in Model)
    {
       <tr>
         <td>@Html.DisplayFor(modelItem => item.Message)</td>
         <td>@Html.DisplayFor(modelItem => item.Body)</td>
       </tr>
    }
 </tbody>

如何将列表转换为JSON,以仅从上面的消息正文中获取模板名称和描述段?最佳实践是存储在数据库表中,并让控制器通过ModelMessage类提取表内容吗?当前类仅在内存中,不会将消息响应写到物理数据库表中。

0 个答案:

没有答案