.NET核心web api获取JSON输入并返回它会导致NULL输出

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

我正在编写一个Web API,它接受任何JSON输入,将其包装在一个信封中(基本上添加一个ID),然后返回它,但我遇到的问题是即使我发送有效的JSON,传入的JSON似乎总是为NULL使用邮递员

简单的控制器如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NWCloudTransactionHost.Controllers
{
    [Route("api/[controller]")]
    public class TransactionInput : Controller
    {
        [HttpPost]
        public IActionResult Index([FromBody] OriginalTransaction originalTransaction)
        {
            var transactionEnvelope = new TransactionEnvelope { Id = Guid.NewGuid(), OriginalTransactionData = originalTransaction };

            return Json(transactionEnvelope);
        }
    }

    public class OriginalTransaction
    {
        public string OriginalTransactionData { get; set; }
    }

    public class TransactionEnvelope
    {
        public Guid Id { get; set; }
        public OriginalTransaction OriginalTransactionData { get; set; }
    }
}
c# json.net asp.net-core-webapi
1个回答
0
投票

使用流阅读器来阅读正文内容流。然后使用contentType: "application/json"返回内容结果。

[HttpPost]
public ContentResult Index()
{
    using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
    {
        // Get the body (json) as a raw string
        var originalTransaction = reader.ReadToEnd();

        // Wrap the transaction
        var id = Guid.NewGuid();
        var envelope = $"{{ \"Id\": \"{id}\", \"OriginalTransactionData\": {originalTransaction} }}";

        // return json
        return Content(envelope, "application/json", Encoding.UTF8);
    }
}

请注意,在此示例中,json上没有验证。如果它不正确(例如,在某处丢失逗号等),答案也将无效。我建议您检查原始字符串originalTransaction是否有效json,然后将其包装在信封中。

Sample

请求

{ "Test": "Hello World" }

响应

{
  "Id": "a9258e99-86cf-4f1d-9e17-0df7ba1dce5e",
  "OriginalTransactionData": {
    "Test": "Hello World"
  }
}

编辑

我的快速回答让我搞砸了一下。这是修订版。我改变了如何读取请求json以及如何发送响应json的方法。此版本现在应该可以使用。还修复了无效的字符串插值并将id放在转义引号中。添加了一个适合我的样本。

尽管有流媒体阅读器,我认为现在更直接。

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